我正在尝试编写一个单元测试来验证它$rootScope.$broadcast('myApiPlay', { action : 'play' });
是否被调用。
这是 myapi.js
angular.module('myApp').factory('MyApi', function ($rootScope) {
var api = {};
api.play = function() {
$rootScope.$broadcast('myApiPlay', { action : 'play' });
}
return api;
});
这是我的单元测试:
describe('Service: MyApi', function () {
// load the service's module
beforeEach(module('myApp'));
// instantiate service
var MyApi;
var rootScope;
beforeEach(function () {
inject(function ($rootScope, _MyApi_) {
MyApi = _MyApi_;
rootScope = $rootScope.$new();
})
});
it('should broadcast to play', function () {
spyOn(rootScope, '$broadcast').andCallThrough();
rootScope.$on('myApiPlay', function (event, data) {
expect(data.action).toBe('play');
});
MyApi.play();
expect(rootScope.$broadcast).toHaveBeenCalledWith('myApiPlay');
});
});
这是我在运行时遇到的错误grunt test
:
PhantomJS 1.9.7 (Windows 7) Service: MyApi should broadcast to pause FAILED
Expected spy $broadcast to have been called with [ 'myApiPlay' ] but it was never called.
我也尝试过expect(rootScope.$broadcast).toHaveBeenCalled()
,但我遇到了类似的错误:Expected spy $broadcast to have been called.
.
我想验证该方法实际上是否已使用正确的参数调用。
谢谢!