How can I test Broadcast event in AngularJS

后端 未结 2 1970
萌比男神i
萌比男神i 2020-12-13 05:42

I have a controller which emits a broadcast event on the rootscope. I would like to test that the broacast event is fired correctly.

My code in my controller looks l

相关标签:
2条回答
  • 2020-12-13 06:28

    Here's how its done with mochaJs, with sinon for mocks and chai for expectations.

    describe("broadcast test", function() {
      beforeEach(inject(function($rootScope){
       sinon.spy($rootScope, "$broadcast")
       scope.foo() //this broadcasts the event. $rootScope.$broadcast("testEvent")
     }))
    
    it("broadcasts the event", inject(function($rootScope){
     expect($rootScope.$broadcast.calledWith("testEvent")).to.be.true
    }))
    
    })
    
    0 讨论(0)
  • 2020-12-13 06:31

    Assuming you're using Jasmine, the following is working great for me.

    ... other unit test setup code ...
    
    var rootScope;
    beforeEach(inject(function($injector) {
        rootScope = $injector.get('$rootScope');
        spyOn(rootScope, '$broadcast');
    }));
    
    describe("my tests", function() {
        it("should broadcast something", function() {
            expect(rootScope.$broadcast).toHaveBeenCalledWith('myEvent');
        });
    });
    

    If you're broadcasting a message and attaching objects to it, you can even test that the objects match expectations

    someObj = { ... something ... };
    expect(rootScope.$broadcast).toHaveBeenCalledWith('someEvent', someObj);
    
    0 讨论(0)
提交回复
热议问题