问题描述
我正在使用 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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)