Unit testing controller which uses $state.transitionTo

后端 未结 3 1824
小蘑菇
小蘑菇 2021-01-11 10:02

within a controller i have a function which uses $state.transitionTo to \"redirect\" to another state.

now i am stuck in testing this function, i get al

3条回答
  •  一个人的身影
    2021-01-11 10:18

    I recently asked this question as a github issue and it was answered very helpfully. https://github.com/angular-ui/ui-router/issues/537

    You should do a $rootScope.$apply() and then be able to test. Note that by default if you use templateUrl you will get an "unexpected GET request" for the view, but you can resolve this by including your templates into your test.

    'use strict';
    
    describe('Controller: CourseCtrl', function () {
    
      // load the controller's module
      beforeEach(module('myApp'));
    
      // load controller widgets/views/partials
      var views = [
        'views/course.html',
        'views/main.html'
      ];
    
      views.forEach(function(view) {
        beforeEach(module(view));
      });
    
      var CourseCtrl,
        scope;
    
      // Initialize the controller and a mock scope
      beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        CourseCtrl = $controller('CourseCtrl', {
          $scope: scope
        });
      }));
    
      it('should should transition to main.course', inject(function ($state, $rootScope) {
        $state.transitionTo('main.course');
        $rootScope.$apply();
        expect($state.current.name).toBe('main.course');
      }));
    });
    

提交回复
热议问题