Unit Testing dependency injection

前端 未结 2 1600
星月不相逢
星月不相逢 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:12

    You'll get this error if one of the injectables module isn't included.

    For instance, you have

    beforeEach(module('home'));
    

    If your $state dependency is not in the home module, you'll need to include that module also. I'm not familiar with $state (I think it's angular-ui's router? Only angular.js services are supposed to start with $). If it's angular ui, this is how you should setup:

    beforeEach(module('ui.router'));
    beforeEach(module('home'));
    

    This way, angular's test runner knows what modules are required to run your tests.

    Really, the inclusion of the home module should do this for you as long as you have the ui.router dependency defined as a dependency of that module. If you have that configured correctly, you may need to look at the order of your files being included for your tests. For example, make sure the ui-router file is being included for your tests and that it is referenced before your home module in karma's config.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题