Angular unit testing window.location

Royer Adames
1 min readDec 14, 2022

--

This is a live search for the best solution

The main roadblock is that:

  • A common way to go to another page with JavaScript/TypeScript is by using window.location
  • location is window.location or location is read-only, and
  • spyOn doesn’t work on read-only

I was expecting spyOnProperty to work but it doesn’t

The current best solution (and only solution) is to replace the window.location with something you can spyOn.

A simple example,

const mockWindow = {
location: {
assign(){}
}
}

const component = new yourComponent(mockWindow)
const href = 'google.com'

const spy = spyOn(mockWindow.location, 'assign')

component.runWindowLocationAssign(href)

expect(spy).toHaveBeenCalledWith(href)
  1. Mock the expected data
  2. insect the data into your component
  3. spyOn the mock data
  4. expect what you need

While this is one of the most simple use cases, its essence of it can be used for more complex cases. This is only one example of how it can be handled.

--

--

Royer Adames
Royer Adames

No responses yet