我在编写我的第一个 React 测试时遇到了一个问题,我的 beforeEach
语句无法正常工作。这是我的测试文件:
import React from 'react';
import { shallow } from 'enzyme';
import Home from '../components/Home';
import IntroText from '../components/IntroText';
import Form from '../components/Form';
describe('<Home />', () => {
beforeEach(() => {
const wrapper = shallow(<Home />);
});
it('renders the IntroText component', () => {
expect(wrapper.find(IntroText).length).toBe(1);
});
it('renders the Form component', () => {
expect(wrapper.find(Form).length).toBe(1);
});
});
这是我的 package.json
的相关部分:
"devDependencies": {
"babel-jest": "^18.0.0",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.23.0",
"jest": "^18.1.0",
"react-scripts": "0.9.0",
"react-test-renderer": "^15.4.2"
},
"dependencies": {
"enzyme": "^2.7.1",
"jest-enzyme": "^2.1.2",
"react": "^15.4.2",
"react-addons-test-utils": "^15.4.2",
"react-dom": "^15.4.2",
"react-router": "^3.0.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
我在测试运行时收到此错误:
ReferenceError: wrapper is not defined
我错过了什么?
最佳答案
您正在 beforeEach
范围内定义包装器 const,像这样将它移到外面:
import React from 'react';
import { shallow } from 'enzyme';
import Home from '../components/Home';
import IntroText from '../components/IntroText';
import Form from '../components/Form';
describe('<Home />', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Home />);
});
it('renders the IntroText component', () => {
expect(wrapper.find(IntroText).length).toBe(1);
});
it('renders the Form component', () => {
expect(wrapper.find(Form).length).toBe(1);
});
});
这样您就可以访问 it
范围内的包装器。
Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.
由于您想在 beforeEach
范围内分配变量并在 it
范围内使用它,因此您必须在公共(public)范围内声明变量,在本例中是 describe
范围。
添加(适用于 mocha 但不适用于 jest):
解决此问题的另一种可能方法是使用 this
关键字(我更喜欢,如果使用 mocha...不适用于 jest)。
import React from 'react';
import { shallow } from 'enzyme';
import Home from '../components/Home';
import IntroText from '../components/IntroText';
import Form from '../components/Form';
describe('<Home />', function() {
beforeEach(function() {
this.wrapper = shallow(<Home />);
});
it('renders the IntroText component', function() {
expect(this.wrapper.find(IntroText).length).toBe(1);
});
it('renders the Form component', function() {
expect(this.wrapper.find(Form).length).toBe(1);
});
});
关于reactjs - react 与 enzyme : why isn't beforeEach() working?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42318799/