如何对我需要测试其发射的角度指令进行茉莉花单元测试?

时间:2016-03-22 22:51:46

标签: javascript angularjs unit-testing jasmine

如何对需要测试其发射的angular指令进行茉莉花单元测试?

这个指令是一个属性指令,在我需要测试的指令中有一个emit。

最好这样做吗?

这是我目前的测试:

   //broadcast test:
     describe('broadcast called', function() {

           var rootScope, testService;

           beforeEach(inject(function(_$rootScope_, $injector) {              
                rootScope = _$rootScope_;

                testService = $injector.get('testFactory');

                spyOn(rootScope, "broadcast");
           })); 

           it('should be broadcast', function() {
              testService.emitTest();
              expect(rootScope.broadcast).toHaveBeenCalledWith('test1');
           });
    });

当前代码:

appservicemod.factory('testFactory', ['$rootScope', function ($rootScope) {

        var emitTest = function(){  

                    $rootScope.$broadcast('test1');

        }   

        return {
            emitTest: emitTest
        } 
    }
]);

2 个答案:

答案 0 :(得分:1)

间谍

spyOn(scope, 'emit');

并且在测试中验证它被称为

expect(scope.emit).toHaveBeenCalledWith('valueItShouldBeCalledWith');

答案 1 :(得分:1)

除了一些问题外,您当前的方法似乎运行良好:

  • 它应该是$broadcast,而不是broadcast无处不在
  • 您的代码中没有beforeEach(module('app'))

如果您解决了这些问题,则可以:http://jsfiddle.net/MMiszy/c4fz58sp/1/

describe('broadcast called', function() {
   var $rootScope, testService;

   beforeEach(module('app'));

   beforeEach(inject(function(_$rootScope_, $injector) {              
        $rootScope = _$rootScope_;
        spyOn($rootScope, "$broadcast");
        testService = $injector.get('testFactory');
   })); 

   it('should broadcast', function() {
      testService.emitTest();
      expect($rootScope.$broadcast).toHaveBeenCalledWith('test1');
   });
});