已经调用了回调,但$ broadcast还没有?

时间:2014-09-10 06:56:09

标签: angularjs unit-testing jasmine

这是我的spec文件,我无法正常工作。

服务的`execute()`方法执行一些AJAX请求。如果收到“401 Unauthorized”,它应该在`$ rootScope`上播放`evt-unauthorized`。

在测试时,我注意到了一些奇怪的事情:`。$ broadcast`似乎从来没有被调用过。 如果我添加一个间谍回调,Jasmine告诉回调实际上已被调用,而`。$ broadcast`仍未触及。

我错过了什么吗?

'use strict';

describe('Service: Some_Service', function () {
    var service, http_backend, rootScope;

    beforeEach(module('Some_Module'));

    beforeEach(inject(function ($httpBackend, $rootScope, Some_Service) {
        http_backend = $httpBackend;
        rootScope = $rootScope.$new();
        service = Some_Service;
        http_backend.whenPOST('http://api.site.com/restricted/area').respond(401);
    }));

    it('should broadcast `evt-unauthorized` on root scope in case of 401', function () {
        var done = false;
        var promise;

        var callback = jasmine.createSpy('callback');
        spyOn(rootScope, '$broadcast');
        rootScope.$on('evt-unauthorized', callback);

        runs(function() {
            promise = service.execute();
            expect(promise).toBeTruthy();
            promise.error(function() {
                done = true;
                //this test succeeds
                expect(callback).toHaveBeenCalled();
                //this one fails
                expect(rootScope.$broadcast).toHaveBeenCalled();
            });
            http_backend.flush();
        });

        waitsFor(function() {
            return done;
        }, 1000);
    });

    afterEach (function () {
        http_backend.verifyNoOutstandingExpectation ();
        http_backend.verifyNoOutstandingRequest ();
    });
});

1 个答案:

答案 0 :(得分:1)

您的服务收到了真实的" $rootScope inject通过rootScope函数,而您在spyOn($rootScope, '$broadcast').andCallThrough(); 上观看,这只是$ rootScope的子视图。

你必须监视$ rootScope的$ broadcast方法:

{{1}}