[英]How to spy on anonymous function using 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;
}
}
});
這是我的測試:
'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'),但因為它是一個匿名函數,所以它沒有任何方法。
謝謝你的幫助。
Daniel Smink的回答是正確的,但請注意Jasmine 2.0的語法已經改變。
notify = jasmine.createSpy().and.callFake(function() {
return false;
});
我還發現如果你只需要一個簡單的實現就可以直接返回一個響應
notify = jasmine.createSpy().and.returnValue(false);
你可以用andCallFake鏈接你的間諜,看看:
http://jasmine.github.io/1.3/introduction.html#section-Spies:_和 andCallFake
//create a spy and define it to change notify
notify = jasmine.createSpy().andCallFake(function() {
return false;
});
it('should be a function', function() {
expect(typeof notify).toBe('function');
});
controller = createController();
scope.isValid('name');
expect(notify).toHaveBeenCalled();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.