[英]Angular 1.5.x/Jasmine - Expected spy to have been called but it was never called
POST-EDIT:我剛剛解決了這個問題,盡管也許有人有更好的解決方案。 我會盡快發布解決方案,但是如果有人有正確的解決方案,我會接受他們的回答。
我正在將應用程序從1.4遷移到1.5,並將所有控制器和指令更改為組件。 我現在有一個測試,該測試曾經無法正常工作,但我需要一些指導。
我試圖監視一種服務方法,並且根據單元測試,它沒有調用。 情況並非如此,因為在運行應用程序時會進行API調用。 這是我收到的消息:
這是我的組件文件:
(function(){
"use strict";
angular.module("app").component("profileComponent", {
templateUrl: "/templates/profile.component.html",
controllerAs: "vm",
bindings: {
resolvedUser: "<"
},
controller: function(ImageService, $state){
const vm = this;
const resolvedUser = this.resolvedUser;
resolvedUser ? vm.user = resolvedUser : $state.go("404");
vm.$onInit = function(){
ImageService.findByName(vm.user.pokemon.name)
.then(function(res){
vm.user.pokemon.id = res.id;
vm.user.pokemon.image = res.sprites.front_default;
vm.user.pokemon.type = res.types[0].type.name;
})
.catch(function(res){
vm.user.pokemon.image = "https://www.native-instruments.com/forum/data/avatars/m/328/328352.jpg?1439377390";
});
}
}
});
})();
這是我的規格文件中的相關部分。 我在測試失敗的地方發表了評論:
describe("profile.component", function(){
var profileComponent, ImageService, $q, $httpBackend, $state, resolvedUser, jazzSpy, IS,
API = "http://pokeapi.co/api/v2/pokemon/";
var RESPONSE_SUCCESS = // very large variable I've omitted for brevity.
beforeEach(angular.mock.module("app"));
beforeEach(angular.mock.module("ui.router"));
beforeEach(inject(function(_ImageService_, _$q_, _$httpBackend_, _$state_, _$rootScope_){
ImageService = _ImageService_;
$q = _$q_;
$httpBackend = _$httpBackend_;
$state = _$state_;
$rootScope = _$rootScope_;
$rootScope.$new();
}));
describe("profileComponent with a valid user and valid Pokemon", function(){
beforeEach(inject(function(_$componentController_){
singleUser = { id: 2, name: "Erlich Bachman", email: "erlich@aviato.com", phone: 4155552233, pokemon: { isPresent: true, name: "celebi"}, icon: { isPresent: false, name: null} };
let bindings = {resolvedUser: singleUser, ImageService: ImageService, $state: $state };
profileComponent = _$componentController_("profileComponent", { $scope: {} }, bindings);
profileComponent.$onInit();
}));
beforeEach(function(){
spyOn(ImageService, "findByName").and.callThrough();
});
it("should set state to resolvedUser", function(){
expect(profileComponent.user).toEqual(singleUser);
});
it("should expect ImageService to be defined", function(){
expect(ImageService.findByName).toBeDefined();
});
it("should call ImageService.findByName() and return Pokemon icon", function(){
expect(profileComponent.user.pokemon.name).toEqual("celebi");
$httpBackend.whenGET(API + "celebi").respond(200, $q.when(RESPONSE_SUCCESS));
$httpBackend.flush();
// This is where the test fails
expect(ImageService.findByName).toHaveBeenCalledWith("celebi");
});
});
如前所述,$ onInit需要在spyOn之后被調用:
beforeEach(function(){
spyOn(ImageService, "findByName").and.callThrough();
profileComponent.$onInit();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.