使用 Jest 运行测试时无法访问窗口属性

sun*_*tro 5 unit-testing reactjs jestjs react-testing-library

我正在尝试访问位于window.sunpietro.configproperty下的property。使用 Jest 运行测试时,我得到TypeError: Cannot read property 'config' of undefined.

我的测试代码如下所示:

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();
    });
});
Run Code Online (Sandbox Code Playgroud)

我正在使用最新版本的 Jest:24.7.1react-testing-library版本:6.1.2.

我如何模拟window属性以便它们可以通过MyModule实例访问?

小智 5

您可以在设置中设置全局变量。我在 package.json 中声明了这个 setupFiles

"jest": {
"setupFiles": [
  "<rootDir>/tests/shim.js",
  ...
],
Run Code Online (Sandbox Code Playgroud)

然后在我的 shim.js 中。我将窗口属性声明为全局的

global.sunpietro : {
 ...
}
Run Code Online (Sandbox Code Playgroud)