我想写一个单元测试,验证$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.
。
我想验证该方法实际上是用正确的参数调用的。
谢谢!
你只需要切换顺序?您可能需要在实际调用之前预期,在您调用它的情况下,然后期待它。你也可以确认通话计数。 – hassassin 2014-09-12 22:12:56
我改变了顺序,同样的错误。 – Andrea 2014-09-12 22:25:49