我建议定义两个单独的单元测试来验证您的行为doThing
功能。尝试以下代码:
(function () {
'use strict';
angular.module('myApp', [])
.controller('MainCtrl', function ($timeout, MyService) {
var vm = this;
vm.invalidInput = true;
vm.doThing = doThing;
function doThing() {
if (vm.invalidInput) {
return;
}
$timeout(function () {
MyService.doThing();
}, 1000);
}
});
})();
(function () {
'use strict';
angular.module('myApp').service('MyService', MyService);
function MyService() {
this.doThing = function () {
// doThing code
};
}
})();
'use strict';
describe('Controller: MainCtrl', function () {
beforeEach(module('myApp'));
var vm,
$timeout,
MyService;
beforeEach(inject(function (_$controller_, _$timeout_, _MyService_) {
$timeout = _$timeout_;
MyService = _MyService_;
vm = _$controller_('MainCtrl', {
$timeout: $timeout,
MyService: MyService
});
}));
it('should call doThing for valid inputs', function () {
spyOn(MyService, 'doThing').andCallThrough();
vm.invalidInput = false;
vm.doThing();
$timeout.flush();
expect(MyService.doThing).toHaveBeenCalled();
});
it('should not call doThing for invalid inputs', function () {
spyOn(MyService, 'doThing').andCallThrough();
vm.invalidInput = true;
vm.doThing();
expect(MyService.doThing).not.toHaveBeenCalled();
});
});
通过第一次测试,我们期望调用MyService.doThing()
功能。
另一方面,如果你有invalidInput
as true
,不应调用前一个函数。
我希望它有帮助。