How to test the existence of a route in Angular using Jasmine?

六眼飞鱼酱① 提交于 2021-01-29 11:27:58

问题


I'm trying to write a test that checks for the existence of a route using Jasmine for Angular application:

import { routes } from './app-routing.module';
import { UsersComponent } from './users/users.component';

describe('routes', () => {
    it('should contain route for /users', () => {
        const expectedRoute = { path: 'users', component: UsersComponent };
        expect(routes).toContain(expectedRoute);
    });
});

but the test fails (probably because of object equality in Javascript How object equality checks work in Javascript?)

How to modify the test to make it work?


回答1:


I have tried it, and it works fine with your code.

There's no problem with equality in the method toContain.

Have you changed const routes to export const routes in your app-routing.module.ts, and import { routes } from './app-routing.module' in your test?

It's the only thing that I had to change in order to test the app.

I have done the following steps:

  • ng new test-routing (saying yes to routing so the app-routing.module.ts is created.
  • Modified app.component.spec.ts with the following code:
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

import { routes } from './app-routing.module';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should contain route for /principal', () => {
        const expectedRoute = { path: 'principal', component: AppComponent };
        expect(routes).toContain(expectedRoute);
  });
});
  • Modified the app-routing.module.ts to add this routes:
export const routes: Routes = [
  { path: '', redirectTo: '/principal', pathMatch: 'full' },
  { path: 'principal', component: AppComponent }
];
  • Run ng test

The test is fine.

If I change the 'principal' path to other, the test fails. If I revert to the good one, the test goes ok.



来源:https://stackoverflow.com/questions/59535910/how-to-test-the-existence-of-a-route-in-angular-using-jasmine

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