【问题标题】:Setting the path in ui-router via $location.path() does not change $state.current通过 $location.path() 在 ui-router 中设置路径不会改变 $state.current
【发布时间】:2014-12-27 08:35:16
【问题描述】:

我正在使用以下代码初始化我的角度控制器:

console.log($state.current);
$location.path('/newpath');
console.log($state.current);

尽管路径已更改,但 $state.current 变量并未更改。我试过 $scope.$apply() 但这给了我一个摘要循环已经在进行中的错误。

请注意,这在我的测试中也不起作用:

it('should route /newpath to the newpath view', function () {
    $location.path('/newpath');
    $rootScope.$apply();

    console.log($location.path());
    console.log($state.current);
    expect($state.current.templateUrl).to.equal('app/newpath/newpath.html');

});

【问题讨论】:

  • 这 3 行是否在您的控制器内部?如果是,那么在那里执行的所有代码都只是属于当前状态...只有在此范围被销毁时...才会启动新状态...
  • 是的,你是对的。我在控制器中使用了所有三行。但是如何进行测试呢?我已经用我的测试规范中的代码更新了我的问题。
  • 但是更改位置不应该反映在状态上吗?目前我正在将角度应用程序从角度路由转换为 ui-router。我已经从我的原始角度路由器代码修改了这个测试代码,其中 $route.current.templateUrl 在通过 $location.path() 设置新位置后发生了变化。
  • 不是 $state.go();用于更改 ui-router 中的路径?也许我弄错了
  • @sbaaaang 是的,如果你仔细阅读我的 cmets(和我的标签),你会发现我正在使用 ui-router,即我正在将我当前的应用程序从 angular-router 转换为 ui -路由器。

标签: angularjs unit-testing angular-ui-router


【解决方案1】:

在为此失去了一整天的头发后,我终于解决了。问题似乎是路由不起作用,因为我的视图模板未被测试识别。 ui-router 的文档指出无效的 templateUrl 会导致路由中断。将视图模板放入模板缓存解决了问题,路由正常工作,测试通过。刚刚将这一行添加到规范中的 beforeEach 函数中:

 beforeEach(inject(function ($templateCache) {
      $templateCache.put('app/newpath/newpath.html', '');
    }));

【讨论】:

  • 真的很有趣,干得好,先生!
【解决方案2】:

正如 zszep 所建议的,这个问题可以通过填充 $templateCache 来解决。

beforeEach(inject(function ($templateCache) {
   $templateCache.put('app/newpath/newpath.html', '');
}));

或者,您想模拟模板的获取,也可以使用 $httpBackend 对模板请求进行存根。

beforeEach(inject(function ($httpBackend) {
    $httpBackend.when('GET', 'app/newpath/newpath.html').respond(200, '');
    $httpBackend.flush();
}));

别忘了flush()

您观察到的根本问题是,如果它无法加载标记或 $stateProvider 定义中定义的所有模板,则转换将失败。发生这种情况时,不会填充 $state 提供程序属性(例如 $state.current)。

【讨论】:

    猜你喜欢
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    相关资源
    最近更新 更多