使用 Jest 进行 运行 测试时无法访问 window 属性
Cannot access window properties when running tests with Jest
我正在尝试访问位于 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。我将 window 属性声明为全局属性,如
global.sunpietro : {
...
}
我正在尝试访问位于 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。我将 window 属性声明为全局属性,如
global.sunpietro : {
...
}