javascript 如何使用 Jasmine 监视匿名函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28580540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to spy on anonymous function using Jasmine
提问by Yonnaled
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.
我正在使用 Jasmine 测试我的 angular 应用程序,并想监视匿名函数。使用 angular-notify 服务https://github.com/cgross/angular-notify,我想知道是否调用了通知函数。
Here is my controller:
这是我的控制器:
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;
}
}
});
And here is my test:
这是我的测试:
'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();
});
});
An obviously return :
一个明显的回报:
Error: No method name supplied on 'spyOn(notify)'
Because it should be something like spyOn(notify, 'method'), but as it's an anonymous function, it doesn't have any method.
因为它应该类似于 spyOn(notify, 'method'),但由于它是一个匿名函数,所以它没有任何方法。
Thanks for your help.
谢谢你的帮助。
回答by Hyman Collins
Daniel Smink's answer is correct, but note that the syntax has changed for Jasmine 2.0.
Daniel Smink 的回答是正确的,但请注意 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);
回答by Dani?l Smink
You could chain your spy with andCallFake see:
您可以使用 andCallFake 链接您的间谍,请参阅:
http://jasmine.github.io/1.3/introduction.html#section-Spies:_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();