Injected $stateParams and $state into jasmine angular js test getting undefined

后端 未结 2 704
青春惊慌失措
青春惊慌失措 2020-12-16 05:09

I am writing a jasmine test for my DetailCtrl. I have 10 json file each with file names like this

1.json
2.json
3.json

in my data folder

相关标签:
2条回答
  • 2020-12-16 06:00

    I think you might be misunderstanding how the router is working with the controller. When you're unit testing a controller, you're not executing a route or entering a ui-router state. Those states and routes are what trigger controllers to be executed when the application is running normally. But in a unit test, you're executing the controller explicitly using $controller. So you're skipping the routing part altogether. Which means you need to mock the object that the ui-router would normally create for you, $stateparams.

    describe('Detail Ctrl', function() {
    
      var scope, ctrl, httpBackend, stateparams, listingId; 
    
      beforeEach(angular.mock.module("backpageApp"));
      //don't need to inject state or stateparams here
      beforeEach(angular.mock.inject(function($controller, $rootScope, _$httpBackend_) {
        httpBackend = _$httpBackend_;
        stateparams = { listingId: 1 }; //mock your stateparams object with your id
    
        //you should be expecting the get request url from the controller, not the route
        httpBackend.expectGET('data/' + stateparams.listingId + '.json').respond([{id: 1 }, {id: 2}, {id:3}, {id:4}, {id:5}, {id:6}, {id:7}, {id:8}, {id:9}, {id:10}]);
        scope = $rootScope.$new(); 
        //pass your mock stateparams object to the controller 
        ctrl = $controller("DetailCtrl", {$scope:scope, $stateParams:stateparams}); 
      }));
    
       it('the images for each listing should exist', function() {
        httpBackend.flush(); 
        //I don't see images set in your controller, but you 
        //could check scope.extrainfo here
        expect(scope.images).toBe(true)
      });
    });
    
    0 讨论(0)
  • 2020-12-16 06:12

    Adding the stateMock.js and then including the module

    beforeEach(function() {
        module('stateMock');
        module('mean');
        module('mean.system');
        module('mean.companies');
      });
    

    code here for stackMock.js: github code for stateMock

    Reference: UI-router interfers with $httpbackend unit test, angular js.

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