gpt4 book ai didi

javascript - 如何使用 Jasmine 监视匿名函数

转载 作者:搜寻专家 更新时间:2023-11-01 04:56:53 26 4
gpt4 key购买 nike

我正在使用 Jasmine 来测试我的 Angular 应用程序并想监视一个匿名函数。使用 Angular 通知服务 https://github.com/cgross/angular-notify , 我想知道是否调用了notify函数。

这是我的 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;
}
}
});

这是我的测试:

'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);

关于javascript - 如何使用 Jasmine 监视匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28580540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com