Unit Testing dependency injection

前端 未结 2 1601
星月不相逢
星月不相逢 2021-02-07 21:39

I am brand new to jasmine and karma. I believe I have the environment setup properly and I am able to run very basic unit tests, but as soon as I try to instantiate a controlle

2条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 22:35

    As you are including the $state dependency in your controller - you need to provide the $state in the controller unit test.

        var $scope = $rootScope.$new(),
        ctrl = $controller('Home', {
                   $scope: $scope,
                   $state: {} //Or inject the state using the injector service and then you can use some jasmine spies to mock the function calls or just to spy on 'em.
              });
        expect(ctrl).not.toBe(null);
    

    Your it block with the changes....

    it('should create "phones" model with 3 phones', inject(function($controller, $rootScope, $state) {
    
        /*
         * 
         * COMMENTING OUT THESE LINES = PASS
         *
         */
            var scope = $rootScope.$new(),
                ctrl = $controller('Home', {$scope:scope, $state: $state});
            expect(ctrl).not.toBe(null);
        }));
    

    However at the setup of my unit tests I like to create function for controller setup as I describe in this setup here.

提交回复
热议问题