unit test spy on $emit

断了今生、忘了曾经 提交于 2019-12-04 22:56:35

According to the docs here, you are correct in your understanding of the difference between $emit and $broadcast. However, I think the problem is in your use of $scope and $rootScope. Your $rootScope will be at the top level of your scope hierarchy. I'm guessing (just by looking at your snippets without being able to see all the code) that your $scope in your controller is a nested controller, meaning that $scope in your controller is a child of the app's $rootScope.

Because of that, when your unit test spys on the $rootScope.$emit function, it is not actually spying on your controller's $scope.$emit() call. Those two "scopes" are different, not the same thing. So, you need to mock the $scope that you provide for the controller and then do a spyOn on that.

For example, in your beforeEach:

var ctrl, scope;

beforeEach(function() {
    module('<INSERT YOUR CONTROLLERS MODULE NAME HERE>'); 
    inject(function($rootScope, $controller) {
        scope = $rootScope.$new();
        ctrl = $controller('<CTRL NAME HERE>', {$scope: scope});
    });
});

This code will actually create a "mock" scope variable and will provide that object to your controller, which you can then do spies and other things with. Such as:

spyOn(scope, '$emit');
// do whatever triggers the "$emit" call
expect(scope.$emit).toHaveBeenCalledWith('resultSend');

I'm pretty sure that should fix your problem. Let me know if that needs more explanation.

If your directive has a controller, you could, and should, test that separately from the directive. That's the whole point of an MVC architecture, you can test the C seperately from the V. ;)

That said, it would be a plain-Jane controller test spec.

Another tip: You should do all of your set up in your beforeEach() block (i.e. spies and whatever) and then do the assertions in your it() blocks.

Finally: Make sure that the spy you're setting up, is on the scope you're passing into the controller you're testing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!