在我的单元测试中,我需要返回一个承诺,以便我的测试不会失败:
describe('refugeeRegister', function () {
var controller, scope, rootScope, window;
beforeEach(function () {
module('refugeeHire');
module("templates");
module('refugeeHire.components.refugee_register', function ($provide) {
$provide.service("authenticationService", function () {
this.signup = jasmine.createSpy("signup").and.returnValue();
this.getCookie=jasmine.createSpy("getCookie");
});
});
});
beforeEach(inject(function ($rootScope, $compile) {
el = angular.element("<refugee-register></refugee-register>");
$compile(el)($rootScope.$new());
$rootScope.$digest();
rootScope = $rootScope;
controller = el.controller("refugeeRegister");
scope = el.isolateScope() || el.scope();
}));
it("should have initialized variables", function () {
expect(scope.vm).toBeDefined();
});
it("should register a user", function () {
scope.register();
expect(rootScope.globals.loading).toBe(true);
expect(authenticationService.signup).toHaveBeenCalled();
});
});
应测试此模块(控制器内部的逻辑):
function refugeeRegister() {
var directive = {
restrict: 'E',
templateUrl: 'components/register/refugee/refugee_register.html',
scope: {},
controller: refugeeRegisterController,
controllerAs: 'vm',
bindToController: true
};
测试中的错误如下:
TypeError: undefined is not an object (evaluating 'authenticationService.signup($scope.vm, "REFUGEE").then') in /Users/fabianlurz/refugeehire/app/components/register/refugee/refugee_register.js (line 73)
register@/Users/fabianlurz/refugeehire/app/components/register/refugee/refugee_register.js:73:60
/Users/fabianlurz/refugeehire/app/components/register/refugee/refugee_register-spec.js:35:19
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 4 of 4 (1 FAILED) (0.004 secs / 0.407 secs)
那么如何在mockService(authenticationService)中返回一个promise?
答案 0 :(得分:1)
对于硬编码的静态分辨率,它可能是
this.signup = jasmine.createSpy("signup").and.returnValue($q.resolve('...');
对于动态解决方案,应在每次通话时发出新承诺:
this.signup = jasmine.createSpy("signup").and.callFake(function () {
return $q.resolve(...);
});