如何测试Angular2的router.navigate? [英] How to test Angular2's router.navigate?

查看:107
本文介绍了如何测试Angular2的router.navigate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在其他单元测试中,我遇到了丢失< router-outlet> 消息的问题,但是为了给出一个很好的隔离示例,我创建了一个AuthGuard来检查是否用户登录后执行某些操作。

I've run into missing <router-outlet> messages in other unit tests, but just to have a nice isolated example, I created an AuthGuard that checks if a user is logged in for certain actions.

这是代码:

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (!this.authService.isLoggedIn()) {
        this.router.navigate(['/login']);
        return false;
    }
    return true;
}

现在我要为此编写单元测试。

Now I want to write a unit test for this.

这是我开始测试的方式:

This is how I start my test:

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            RouterTestingModule.withRoutes([
                {
                    path: 'login',
                    component: DummyComponent
                }
            ])
        ],
        declarations: [
            DummyComponent
        ],
        providers: [
            AuthGuardService,
            {
                provide: AuthService,
                useClass: MockAuthService
            }
        ]
    });
});

我创建了一个不执行任何操作的DummyComponent。
现在我的测试。假设服务返回false并触发 this.router.navigate(['/ login'])

I created a DummyComponent that does nothing. Now my test. Pretend that the service returns false and that it triggers this.router.navigate(['/login']):

it('should not let users pass when not logged in', (): void => {
    expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
});

这将引发异常,显示找不到要加载的主要出口。
显然,我可以使用 toThrow()代替 toBe(false),但这似乎没有就像一个非常明智的解决方案。由于我在这里测试服务,因此没有可放置< router-outlet> 标签的模板。我可以模拟路由器并创建自己的导航功能,但是RouterTestingModule有什么意义呢?

This will throw an exception with "Cannot find primary outlet to load". Obviously I can use toThrow() instead of toBe(false), but that doesn't seem like a very sensible solution. Since I'm testing a service here, there is no template where I can put the <router-outlet> tag. I could mock the router and make my own navigate function, but then what's the point of RouterTestingModule? Perhaps you even want to check that navigation worked.

推荐答案


我可以模拟路由器并制作我的路由器自己的导航功能,但是RouterTestingModule有什么意义呢?也许您甚至想检查一下导航是否正常。

I could mock the router and make my own navigate function, but then what's the point of RouterTestingModule? Perhaps you even want to check that navigation worked.

没有真正的意义。如果他只是对auth Guard的单元测试,则只需模拟并监视该模拟即可检查是否使用 login调用了 navigate 方法参数

There's no real point. If his is just a unit test for the auth guard, then just mock and spy on the mock to check that it's navigate method was called with the login argument

let router = {
  navigate: jasmine.createSpy('navigate')
}

{ provide: Router, useValue: router }

expect(authGuardService.canActivate(<any>{}, <any>{})).toBe(false);
expect(router.navigate).toHaveBeenCalledWith(['/login']);

这通常是应该编写 unit 测试的方式。要尝试测试任何实际的真实导航,可能会落入端到端测试的范围之内。

This is how unit tests should normally be written. To try to test any actual real navigation, that would probably fall under the umbrella of end-to-end testing.

这篇关于如何测试Angular2的router.navigate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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