我想寫一個單元測試,驗證$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