問題描述
我正在使用 Jasmine 測試我的 Angular 應用程序并希望監視一個匿名函數.使用 angular-notify 服務 https://github.com/cgross/angular-notify,我想要知道通知函數是否被調用.
I'm using Jasmine to test my angular application and want to spy on an anonymous function. Using angular-notify service https://github.com/cgross/angular-notify, I want to know whether notify function have been called or not.
這是我的控制器:
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;
}
}
});
這是我的測試:
'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();
});
});
一個明顯的回報:
Error: No method name supplied on 'spyOn(notify)'
因為它應該是類似 spyOn(notify, 'method') 的東西,但是由于它是一個匿名函數,所以它沒有任何方法.
Because it should be something like spyOn(notify, 'method'), but as it's an anonymous function, it doesn't have any method.
感謝您的幫助.
推薦答案
Daniel Smink 的答案是正確的,但請注意 Jasmine 2.0 的語法已更改.
Daniel Smink's answer is correct, but note that the syntax has changed for Jasmine 2.0.
notify = jasmine.createSpy().and.callFake(function() {
return false;
});
如果您只需要一個簡單的實現,我還發現直接返回響應很有用
I also found it useful to just directly return a response if you only need a simple implementation
notify = jasmine.createSpy().and.returnValue(false);
這篇關于如何使用 Jasmine 監視匿名函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!