0

When unit testing a component that depends on being on a certain route, how do I set the current URL?

component.html

<button class="menu-button" *ngIf="router.url === '/home'">

component.spec.ts

it('menu button should toggle side navs', () => {
  const buttonEl = toolbarElement.querySelector('.menu-button');

  (buttonEl as HTMLElement).click();
  expect(navigationServiceSpy.sideNavLeftToggle).toHaveBeenCalled();
});

buttonEl is undefined because I cannot set the current route of the component. I have tried the following without luck:

  • navigating to the URL in the unit test using router.navigate(['/home']) on the 'real' router
  • spying on the router and navigating to the URL

In both cases router.url remains undefined and I cannot get my conditional element to render :(

Florestan Korp
  • 662
  • 2
  • 12
  • 24
  • Please share your test, the component code and the test-setup code. – Philipp Meissner Sep 30 '21 at 11:42
  • 1
    Does this answer your question? [jasmine angular 4 unit test router.url](https://stackoverflow.com/questions/53314181/jasmine-angular-4-unit-test-router-url) – possum Sep 30 '21 at 12:33

0 Answers0