I'm trying to access a property that is located under window.sunpietro.config
property. When running tests with Jest I'm getting TypeError: Cannot read property 'config' of undefined
.
My test code looks like the following:
import React from 'react';
import { render, cleanup } from 'react-testing-library';
import MyModule from '../my.module';
import { myConfigMock } from '../../../../jest.window.mock';
afterEach(cleanup);
beforeEach(() => {
window.sunpietro = { ...myConfigMock };
// window.sunpietro.config = {};
});
describe('MyModule', () => {
test('The module renders correctly', () => {
const { getByTestId } = render(<MyModule />);
getByTestId('my-tabs').toBeDefined();
getByTestId('my-panels').toBeDefined();
});
});
I'm using the latest version of Jest: 24.7.1
and the react-testing-library
version: 6.1.2
.
How can I mock the window
properties so they're accessible by MyModule
instance?
Jest's spyOn method is used to spy on a method call on an object. It is also very beneficial in cases where the Jest mock module or mock function might not be the best tool for the job on hand. While writing unit tests you only test one particular unit of code, generally a function.
jsx'), in my jest test files? Yes, omit the file extension and Jest will handle the rest.
setTimeout(timeout) Set the default timeout interval for tests and before/after hooks in milliseconds. Note: The default timeout interval is 5 seconds if this method is not called. Example: jest.
Some familiarity with Jest as a test runner or framework is helpful but not required. Because Jest is pre-packaged with Create React App, you do not need to install it separately.
You could set global variables in your setup. I have this setupFiles declared in my package.json
"jest": {
"setupFiles": [
"<rootDir>/tests/shim.js",
...
],
Then in my shim.js. I am declaring window properties as global like
global.sunpietro : {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With