[英]Jasmine + AngularJS: How to test $rootScope.$broadcast being called with arguments?
我正在嘗試編寫一個單元測試來驗證$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.
。
我想驗證是否已使用正確的參數調用該方法。
謝謝!
你的測試沒有通過的原因是因為你正在監視錯誤的$ broadcast功能。 在beforeEach設置中,您要求注入$ rootScope,然后通過調用$ rootScope來創建子范圍。$ new()。
$ rootScope。$ new()的返回值不再是rootScope,而是根范圍的子節點。
beforeEach(function () {
//inject $rootScope
inject(function ($rootScope, _MyApi_) {
MyApi = _MyApi_;
//create a new child scope and call it root scope
rootScope = $rootScope.$new();
//instead don't create a child scope and keep a reference to the actual rootScope
rootScope = $rootScope;
})
});
在你的游戲功能中,你在$ rootScope上調用$ broadcast,但在你的測試中你正在監視$ rootScope的孩子。
$rootScope.$broadcast('myApiPlay', { action : 'play' });
所以要把它包起來,刪除對$ rootScope。$ new()的調用,然后只調查注入器給你的$ rootScope。 提供給您的單元測試的$ rootScope與提供給您的API服務的$ rootScope相同,因此您應該直接在$ rootScope上進行間諜活動。
查看plunkr http://plnkr.co/edit/wN0m8no2FlKf3BZKjC4k?p=preview
它對您有所幫助https://stackoverflow.com/a/17227264/2594499您的測試不明確。 避免在條件,回調和類似的事情中使用“expect”。 如果你的情況不成立,你就得到了沒有斷言的測試。
使用函數的第二個參數會更好:
.toHaveBeenCalledwith('someEvent', someObj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.