测试路由时如何使用tick()函数?

问题描述 投票:0回答:1

我试图对根组件app.component.ts进行单元测试,其中app.component.html HTML只包含<router-outlet></router-outlet>

因此,应用程序基于以下路由器配置使用http://localhost:port/login立即启动redirectTo

`export const appRoutes: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full'},
    { path: 'login', component: LoginComponent},
    { path: 'add', component: RegisterComponent},
    ....
];
export const routes: ModuleWithProviders = RouterModule.forRoot(appRoutes);` 

我的问题是当我在ng test --sm=false中使用/使用以下方法运行app.component.spec.ts时:

it( 'navigate to "" redirects you to /login', fakeAsync(() => {
        router.navigate([""]);
        tick();
        expect(location.path()).toBe("/login");
    })
);

测试失败,它显示:Expected '' to be '/login'但是当我使用这个方法/语法时:

it( "root should be able to navigate to `/login`", fakeAsync(() => {
        fixture.detectChanges();
        // initial navigation
        router.navigate([""]).then(() => {
           expect(router.url).toEqual("/login");
        });
     })
);

然后测试通过。

所以,在这种情况下,我无法弄清楚使用tick()函数等究竟是什么问题。

什么是最佳实践 - 尝试使用第一种方法并修复失败的测试,或者第二项功能是否足够我的测试?

我应该在第一种方法中更改/修复什么才能使用它而不是第二种?

对于更多输入,这里是角度和角度cli版本我使用:

Angular CLI: 1.5.0
Node: 8.0.0
OS: darwin x64
Angular: 5.0.3
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cdk: 5.0.0-rc.2
@angular/cli: 1.5.0
@angular/material: 5.0.0-rc.2
@angular-devkit/build-optimizer: 0.0.33
@angular-devkit/core: 0.0.21
@angular-devkit/schematics: 0.0.37
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.0
@schematics/angular: 0.1.7
typescript: 2.4.2
webpack: 3.8.1
angular unit-testing
1个回答
2
投票

问题是tick函数不会等到promise在这种情况下解决。您可以使用tick(2000)或更高的值来等待承诺返回,但它不准确。

在url导航路由器解析promise时,在第二个函数中。所以你不需要盲目地设置超时值以等到承诺。所以第二种方法更准确

© www.soinside.com 2019 - 2024. All rights reserved.