Angular unit test coverage for Window.Location.Href

Viewed 995

I am using Angular 7 and trying to write some unit tests to cover this simple component.

export class DialogComponent implements OnInit {
 
  appError: any;
  httpErrorResponse: HttpErrorResponse;
 
  constructor(
    public dialogRef: MatDialogRef<DialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) {
    Eif (data && typeof AppError) {
      this.appError = data;
    } else {
      throw new Error('unknown error type');
    }
  }
 
  ngOnInit() {
  }
 
  navigate(url: string): void {
    if (!url) {
      throw new Error('url is undefined');
    }
    window.location.href = url;
  }
 
}

I unfortunately cant get my test cases to check for the throw new Error('unknown error type'); and the entire navigate function.

Here is an example of what i've attempted: This is successful however, the cover is still not clearing up, meaning that i was unsuccessful.

it('should run #navigate()', async () => {
    const dialog = spyOn(component, 'navigate');
    component.navigate('http://dummy.com');
    expect(dialog).toHaveBeenCalledWith('http://dummy.com');

});

Any guidance would be appreciated


Edit: AppError

export class AppError {
    title?: string;
    customMessage?: string;
    message?: string;
    popUpCloseable: boolean;
    navigation?: string;
    details?: string;
    status?: any;
    code?: any;
    name?: any;
    url?: string;
    statusText?: string;
    customTextButton?: string;
}
1 Answers

When using window inside an Angular component, it is common practice to inject it as a WindowRef service. This makes your application more consistent with the principle of dependency injection, and simplifies your tests.

You can simply create the following wrapper service:

import { Injectable } from '@angular/core';

function getWindow (): any {
    return window;
}

@Injectable()
export class WindowRefService {
  get nativeWindow (): any {
    return getWindow();
  } 
}

As far as your tests, you can inject it by

beforeEach(() => {

  mockWindowRefService = { nativeWindow: {}};

  TestBed.configureTestingModule({
    providers: [
      { provide: WindowRefService, useValue: mockWindowRefService }
   ]  
 });
});
Related