如何模拟/在角单元测试引发$ routeChangeSuccess? [英] How to mock/trigger a $routeChangeSuccess in Angular unit tests?

查看:129
本文介绍了如何模拟/在角单元测试引发$ routeChangeSuccess?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于附着在$ routeChangeSuccess事件的处理程序来更新$ rootScope称号属性:

Given a handler attached to the $routeChangeSuccess event to update the title property on $rootScope:

$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
  $rootScope.title = 'My title';
});

在单元测试中,我想到的是执行路线的变化将更新标题属性:

in unit tests, I expect that performing a route change would update the title property:

it('should set a title on $routeChangeSuccess', function () {
  $location.path('/contacts');
  $rootScope.$apply();

  expect($rootScope.title).toBe('My title');
});

不过,在$ routeChangeSuccess处理程序code从不执行的测试。它执行罚款和更新运行在浏览器应用程序时的标题。

However, the code in the $routeChangeSuccess handler never executes in tests. It executes fine and updates the title when running the application in the browser.

我怎样才能触发测试一个$ routeChangeSuccess事件?是否有测试任意code更好的办法是连接到$ rootScope。在$('$ routeChangeSuccess',...)或其他$ routeChange事件?

How can I trigger a $routeChangeSuccess event in tests? Is there a better approach to testing any arbitrary code that is attached to $rootScope.$on('$routeChangeSuccess', ...) or other $routeChange events?

推荐答案

尝试发送自己的事件。

$rootScope.$broadcast('$routeChangeSuccess', eventData);

这篇关于如何模拟/在角单元测试引发$ routeChangeSuccess?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆