Reputation: 971
I'm writing unit tests that require the window.location.href to be defined The first unit test is created as follows
describe('myMethod()', () => {
beforeEach(() => {
global.window = Object.create(window);
Object.defineProperty(window, 'location', {
configurable: true,
value: {
href: 'http://localhost:7777/mainPoint?param=val1',
},
});
});
it('should call with val1', () => {
myMethod();
expect(myService.detectURLCall).toHaveBeenCalledWith('http://localhost:7777/mainPoint?param=val1'); // passes
});
describe('mySecondMethod()', () => {
beforeEach(() => {
global.window = Object.create(window);
Object.defineProperty(window, 'location', {
configurable: true,
value: {
href: 'http://localhost:7777/mainPoint?param=val2',
},
});
});
it('should call with val2', () => {
myMethod();
expect(myService.detectURLCall).toHaveBeenCalledWith('http://localhost:7777/mainPoint?param=val2'); // fails, the received call was ending with =val1
})
I know that the jest unit tests run in parallel, I tried doing clearMocks() in an afterEach() inside myMethod() test suite but it did not help and my second test suit still detects what we defined in the first one..
Upvotes: 0
Views: 941
Reputation: 176
The following looks to be a good solution for your issue:
https://github.com/simon360/jest-environment-jsdom-global (built on top of jest's built-in jest-environment-jsdom, and has a good readme that directly relates)
This ensures that you have one defined environment per file, which would definitely be the root issue as you said.
Upvotes: 1