无法从全局配置访问

时间:2019-04-09 03:05:31

标签: reactjs jestjs enzyme

我正在尝试在我的react应用程序中为酶使用全局配置。 我阅读了一些有关它的文档,并想尝试一下。 但是我一定很想念东西。

这是我的 Grid 组件的测试脚本(Grid.test.js)。请注意,此文件与Componenet文件本身位于同一文件夹中。我没有为测试脚本维护任何单独的“测试”文件夹-

import React from 'react';
import Grid from './Grid';

test('Grid Renders',()=>{    
const wrapper=shallow(<Grid></Grid>)
expect(wrapper.length).toBe(1);
})
  • 开玩笑地警告我找不到

要创建全局配置,这是我遵循的步骤-

  1. 在应用程序的根文件夹下创建了一个名为“ test”的文件夹。 该文件夹有一个文件-'setupTests.js'

这是文件的内容-

import React from 'react';
import Enzyme, { shallow, render, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';;

Enzyme.configure({ adapter: new Adapter() });

global.React = React;
global.shallow = shallow;
global.render = render;
global.mount = mount;
  1. 在“ src”文件夹中创建了一个笑话配置文件( jest.config.js ),这就是该文件的内容-

    module.exports = {
        setupFiles: ['<rootDir>/test/setupTests.js']        
    };
    
  2. 我需要在package.json中添加任何内容吗?

1 个答案:

答案 0 :(得分:1)

由于您在“ src”文件夹中有hyper个文件。 jest.config.js代表“ src”文件夹。

<rootDir>

这就是为什么您遇到问题。您可以通过

解决它

解决方案1 ​​

在根级别移动module.exports = { // Here "<rootDir>" is "src" folder setupFiles: ['<rootDir>/test/setupTests.js'] }; 文件。

因此jest.config.js中的<rootDir>表示您应用的根目录。

Soution 2

setupFiles: ['<rootDir>/test/setupTests.js']移动到“ src”文件夹中。

并添加到脚本/test/setupTests.js

解决方案3

"test": "jest --config ./src/jest.config.js"保持在根级别。

删除/test/setupTests.js文件。

并将配置添加到jest.config.js

package.json