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
Useselector Not Updating When Store Has Changed in Reducer. Reactjs Redux
Css Div Height Not Expanding to Fit Content or Wrapping Content
Get Array of Values from Multiple Inputs Using Jquery
How to Download a File With Node.Js (Without Using Third-Party Libraries)
Remove Time from Gmt Time Format
Bootstrap Button Drop-Down Inside Responsive Table Not Visible Because of Scroll
How to Bind Dynamic Check Boxes Value Using Ng-Model
Filter Input Text to Enter Only Number and Not Even Decimal
How to Mock the JavaScript Window Object Using Jest
Uploading Multiple Files Using Formdata()
How to Split Date and Time from the Datetime Variable in JavaScript
Angular: How to Get Default @Input Value
Nodejs MySQL Get Correct Timestamp Format
React Enable Button After All Form Fields Are Not Empty
Text Box to Appear When a Radio Button Is Selected
Puppeteer Wait Until Page Is Completely Loaded
How to Get the Ajax Response from Success and Assign It in a Variable Using Jquery