我正在尝试访问位于 window.sunpietro.config
属性下的属性。使用 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();
});
});
我正在使用最新版本的 Jest:24.7.1
和 react-testing-library
版本:6.1.2
。
如何模拟 window
属性,以便可以通过 MyModule
实例访问它们?
最佳答案
您可以在设置中设置全局变量。我在我的 package.json 中声明了这个 setupFiles
"jest": {
"setupFiles": [
"<rootDir>/tests/shim.js",
...
],
然后在我的 shim.js 中。我将窗口属性声明为全局属性,例如
global.sunpietro : {
...
}
关于reactjs - 使用 Jest 运行测试时无法访问窗口属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55724420/