How to Mock the JavaScript Window Object Using Jest

Jest mock window object before importing a dependency

es6 imports are "hoisted", meaning wherever you write them in the code, they'll get processed before the importing module is executed, so the imported module is always executed before the importing module. In your case, this means foo.js executes before foo.test.js, so even if you properly mock your property of window in your tests, foo.js will not see your mock.

You can get around this by using require in your tests to import foo.js after the property of window has been mocked.

// foo.test.js
window.myValue = { nestedValue: MOCK_NESTED_VALUE };

const { dependency } = require('./foo');

describe('...', () => {
it('...', () => {
// use dependency
})
})

As other answers have pointed out, if myValue is one of existing "sytem" properties of window such as window.location, you might have to delete it first. When deleting, don't forget to back it up so that you can restore it when cleaning up after your test.

How do I mock a custom property of the window object in Jest?

You should assign dataObj to the value of the descriptor.

E.g.

index.js:

export function main(event) {
window.dataObj.send(event.name, 'ldo');
}

index.test.js:

import { main } from './';

describe('66574843', () => {
it('should pass', () => {
const dataObj = {
send: jest.fn(),
};

Object.defineProperty(window, 'dataObj', {
value: dataObj,
});

main({ name: 'teresa' });
expect(dataObj.send).toBeCalledWith('teresa', 'ldo');
});
});

test result:

 PASS  examples/66574843/index.test.js
66574843
✓ should pass (4 ms)

----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.755 s

Testing window.location in jest

I figured out a way to mock windows.location. I am attaching a code snippet which will be helpful for others who are trying to mock it.

beforeEach(() => {
delete window.location;
window.location = Object.assign(new URL("https://dickssportinggoods.com"))
});

it('mocks windows.location function', () => {
//call your function.
expect(global.window.location).toBe("https://yoururl.com/?status=SUCCESS");
});

Stubbing window functions in Jest

In jest you can just overwrite them using global.

global.confirm = () => true

As in jest every test file run in its own process you don't have to reset the settings.



Related Topics



Leave a reply



Submit