Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access window properties when running tests with Jest

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?

like image 669
sunpietro Avatar asked Apr 17 '19 09:04

sunpietro


People also ask

What does spyOn do in jest?

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.

Does jest work with JSX?

jsx'), in my jest test files? Yes, omit the file extension and Jest will handle the rest.

What is jest setTimeout?

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.

Do you need jest for react testing library?

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.


1 Answers

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 : {
 ...
}
like image 55
Ange Avatar answered Oct 16 '22 19:10

Ange