0

I have a function which looks for place in the url and if found, the function will remove it and update location.href. How to write a test?

export class Auth0IdentityService extends IdentityService {
    constructor() {}

    removePlaces(): void {
        const url = new URL(window.location.href)
        if ((url.searchParams.get("place")) {
            url.searchParams.delete("place");
        window.location.href = url.href;
        }
    }
}

`

My it block is:

it('should remove place from url', async () => {
    const spy = spyOnProperty(window.location, 'href', 'get').and.returnValue("http://localhost:3000/?place=xxxx");
    component.removePlaces()
    expect (window.location.href).toBe ("http://localhost:3000/?place=xxxx")
})

`

It end up with error message "href is not declared configurable".

Thank A
  • 3
  • 2

1 Answers1

0

You have to do something like this to be able to inject the Window object into the constructor. Injecting the Window object in the constructor makes unit testing much easier: https://stackoverflow.com/a/40292188/7365461.

Do what the answer shows in the @NgModule in the AppModule.

Then make the following changes to your service:

export class Auth0IdentityService extends IdentityService {
    // Get a handle on the Window object
    constructor( @Inject('Window') private window: Window) { }

    removePlaces(): void {
        // refer to it as this.window
        const url = new URL(this.window.location.href)
        if ((url.searchParams.get("place")) {
            url.searchParams.delete("place");
        this.window.location.href = url.href;
        }
    }
}

And then mock the window in your test

let mockWindow: any;
....

// mock the window however you wish
mockWindow = { location: { href:: 'http://localhost:3000/?place=xxxx' } };
TestBed.configureTestingModule({
  ...,
  providers: [
    ....
    // Provide the mock for the real window
    { provide: 'Window', useValue: mockWindow }
    ....
  ],
  ...
});

And then try to test:

it('should remove place from url', async () => {
    component.removePlaces()

    expect (mockWindow.location.href).toBe("http://localhost:3000/?place=xxxx")
})
AliF50
  • 16,947
  • 1
  • 21
  • 37