Модульное тестирование Angular с кармой / жасмином: - PullRequest
0 голосов
/ 20 февраля 2020

Я вставил условие if-else в свой компонент, чтобы после входа в систему я был перенаправлен на указанный c URL. Однако мой модульный тест теперь не проходит со следующей ошибкой:

1) должен создать

AnotherComponent

 Uncaught Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'testroute'

Без условия if else все работает нормально, поэтому я уверен, что это является причиной моей проблемы. Самое смешное, что я не тестирую ничего, что связано с кодом внутри моего жизненного цикла ngOnInit (). Более забавно то, что не тест для MyComponent не проходит, а тест для другого компонента.

Мой компонент (MyComponent) выглядит так:

export class MyComponent implements OnInit {

  routes = Constants.routes;

  constructor(private router: Router,
    private myService: MyService) {
  }

  ngOnInit() {
    if (this.myService.context === 'TEST') {
      this.router.navigate([routes.testroute + this.myService.context]);
    } else {
      this.router.navigate([routes.testroute]);
    }
  }
}

Шаблон выглядит следующим образом:

<router-outlet></router-outlet>

Модульный тест неисправного компонента выглядит следующим образом:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([]),
      ],
      providers: [
        PathLocationStrategy
      ],
      declarations: [AnotherComponent],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AnotherComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

1 Ответ

3 голосов
/ 20 февраля 2020

Вам необходимо настроить маршрут при импорте модуля тестирования маршрутизатора. Я обычно настраиваю маршруты с фиктивными компонентами.

TestBed.configureTestingModule({
  imports: [
    CommonModule,
    RouterTestingModule.withRoutes([
      // add routes here
      { path: 'testroute', component: DummyComponent }
    ]),
 ],
 providers: [
    PathLocationStrategy
  ],
 declarations: [AnotherComponent],
}).compileComponents();
@Component({ template: '' })
class DummyComponent { }
...