Angular: Unit Testing Routing : Expected '' to be '/route'

亡梦爱人 提交于 2019-12-05 12:13:04

You forgot to import routes to the RouterTestingModule, in your test file.

You have to add export keyword to your const routes in your AppRoutingModule file, then you can import the routes in your test file ( and add them in your test configuration).

import {routes} from '...'; // I don't have the app-routing.module file path.
...
...
...
 beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes), <-- I added the routes here.
                FormsModule , DxTemplateModule , HttpModule 
  ],
      providers:    [SessionService , HttpService ],
      declarations: [
        AppComponent,
        LoginComponent,
        WelcomeComponent,
        ApplicationParametersComponent,
        InscriptionComponent
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]

    });

    router = TestBed.get(Router);
    location = TestBed.get(Location);

    fixture = TestBed.createComponent(AppComponent);
    router.initialNavigation();
  });

If you don't load routes in the router testing modules, it won't be able to know where to go when you navigate, so it will get back to original page with an error in console.

The tutorial you followed has a very strange way to handle routing because tick() is used for fakeAsync tests and this is a real async one. So you have to use the Promise<boolean> returned by router.navigate:

it('navigate to "inscription" takes you to /inscription', () => {
    router.navigate(['inscription']).then(() => {
        expect(location.path()).toBe('/inscription');
    });
});

As you see you can also remove fakeAsync because this is not fake, it's an async call.

See it on plunkr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!