Angular + Jasmine + Karma Test 'window.location.href'

Viewed 204

I've been pretty roadblocked on trying to figure out how to use Jasmine and Karma to test this piece of code. Essentially, I'm trying to write a test for when the user navigates back to the home page. Currently, when I run the test it opens the browser and gets stuck until I close the browser. Any help is greatly appreciated!

component.ts

  export class HeaderComponent implements OnInit {
  constructor(private router: Router) {}

  ngOnInit(): void {}

  goToHome(): void {
    window.location.href = '/';
  }
}

component.spec.ts

  describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

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

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

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

  
  it('should call goToHome and navigate home', () => {
    component.goToHome();
    expect(component).toBeTruthy();
  });
});
1 Answers

In Angular, you don't want to use window.location to navigate to a page. You should use router.navigate(['/']). This will first fix your Karma issue.

If your router is nested/complex please add more detail to your question.

Your test can assert that router.navigate was called, or you can use the RouterTestingModule.

Related