Yon*_*led 5 javascript testing jasmine angularjs karma-jasmine
我正在使用Jasmine来测试我的角度应用程序,并希望监视一个匿名函数.使用angular-notify服务https://github.com/cgross/angular-notify,我想知道是否已经调用了通知功能.
这是我的控制器:
angular.module('module').controller('MyCtrl', function($scope, MyService, notify) {
$scope.isValid = function(obj) {
if (!MyService.isNameValid(obj.name)) {
notify({ message:'Name not valid', classes: ['alert'] });
return false;
}
}
});
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
'use strict';
describe('Test MyCtrl', function () {
var scope, $location, createController, controller, notify;
beforeEach(module('module'));
beforeEach(inject(function ($rootScope, $controller, _$location_, _notify_) {
$location = _$location_;
scope = $rootScope.$new();
notify = _notify_;
notify = jasmine.createSpy('spy').andReturn('test');
createController = function() {
return $controller('MyCtrl', {
'$scope': scope
});
};
}));
it('should call notify', function() {
spyOn(notify);
controller = createController();
scope.isValid('name');
expect(notify).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
一个明显的回报:
Error: No method name supplied on 'spyOn(notify)'
Run Code Online (Sandbox Code Playgroud)
因为它应该像spyOn(notify,'method'),但因为它是一个匿名函数,所以它没有任何方法.
谢谢你的帮助.
Daniel Smink的回答是正确的,但请注意Jasmine 2.0的语法已经改变.
notify = jasmine.createSpy().and.callFake(function() {
return false;
});
Run Code Online (Sandbox Code Playgroud)
我还发现如果你只需要一个简单的实现就可以直接返回一个响应
notify = jasmine.createSpy().and.returnValue(false);
Run Code Online (Sandbox Code Playgroud)