0
POST-EDIT:我剛剛解決了這個問題,但也許有人有一個更好的解決方案。我會很快發佈我的解決方案,但如果有人有正確的解決方案,我會接受他們的答案。角1.5.x /茉莉 - 預期的間諜被稱爲,但從未被稱爲
我將我的應用程序從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: "[email protected]", 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之前調用。 – estus
你得到了正確的答案! –