Angular unit testing window.location
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)
- Mock the expected data
- insect the data into your component
- spyOn the mock data
- 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.