【问题标题】:AngularJS Jasmine test $state.current emptyAngularJS Jasmine 测试 $state.current 为空
【发布时间】:2018-03-23 13:17:42
【问题描述】:

我编写了一个组件,其中 $onInit 会检查 $state 以设置一些变量。

在我的路由器配置中,我有:

$stateProvider.state('app.students', {
    abstract: true,
    url: '/students'
});

$stateProvider.state('app.students.active', {
    url: '/active',
    component: 'listing',
    data: {
        tab: 'active'
    }
});

在我的组件中,我正在做一些事情:

const vm = this;
vm.myStateName = $state.current.name;
vm.myStateData = $state.current.data;

在运行应用程序时效果很好。

但是,在进行测试时,我遇到了一个困扰我多年的问题。这是我测试中所写内容的简化版本:

let $state, $rootScope, componentCtrl = null;

beforeEach(angular.mock.inject((_$state_, _$rootScope_, $componentController) => {
    $state = _$state_;
    $rootScope = _$rootScope_;
    componentCtrl = $componentController('listing', {
        $scope: $rootScope.$new(),
        $state: $state
    });
}));

it('Should append the current model', () => {
    $state.go('app.students.active');
    $rootScope.$digest();
    componentCtrl.$onInit();
    expect(componentCtrl.data.tab).toEqual('active');
});

但这永远不会被分配任何东西。

如果我尝试在测试中记录 $state.current,我总是会以“空”类型状态结束,例如 {"name":"","url":"^","views":null,"params":{"#":{"value":null,"type":"hash","dynamic":true}},"abstract":true}

经过大量研究后,我发现我不是唯一遇到此问题的人,但没有关于这些线程的建议完全解决了我的问题: https://github.com/angular-ui/ui-router/issues/1627

是因为我的父母是抽象路线吗?如果是这样,我如何访问嵌套的子状态?

【问题讨论】:

    标签: angularjs jasmine angular-ui-router karma-jasmine


    【解决方案1】:

    在下面尝试它肯定会起作用,因为它稍后会被填充并且浏览器会做出反应。尝试将带有 $state 的块包含到 $timeout() 中。在获取值之前等待 $digest 循环结束是一个技巧。

    $timeout(function() { console.log("******",$state.current.name); },1000);
    

    笨蛋 http://plnkr.co/edit/xIpkOeaQ3XyhB5gz1SnJ?p=preview

    【讨论】:

      猜你喜欢
      • 2016-02-14
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2015-03-05
      • 2014-05-04
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多