Tôi đang cố gắng viết một bài kiểm tra đơn vị xác minh rằng $rootScope.$broadcast('myApiPlay', { action : 'play' });
được gọi.
Đây là myapi.js
angular.module('myApp').factory('MyApi', function ($rootScope) {
var api = {};
api.play = function() {
$rootScope.$broadcast('myApiPlay', { action : 'play' });
}
return api;
});
Và đây là Unit Test của tôi:
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');
});
});
Đây là lỗi tôi nhận được khi chạy 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.
Tôi cũng đã thử với expect(rootScope.$broadcast).toHaveBeenCalled()
và tôi gặp lỗi tương tự: Expected spy $broadcast to have been called.
.
Tôi muốn xác minh rằng phương thức đó thực sự đã được gọi với thông số phù hợp.
Cảm ơn bạn!
Bạn chỉ cần chuyển đơn đặt hàng? Bạn có thể cần phải mong đợi trước khi nó thực sự được gọi, trong trường hợp của bạn, bạn gọi nó, sau đó mong đợi nó. Bạn cũng có thể xác nhận số cuộc gọi đó. – hassassin
Tôi đã chuyển lệnh, cùng một lỗi. – Andrea