我正在编写我的第一个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我遗漏了什么?
发布于 2017-02-19 02:07:30
您在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作用域内的包装器。
常量是块范围的,与使用Let语句定义的变量非常相似。常量的值不能通过重新赋值来更改,也不能重新声明。
由于您希望在beforeEach范围内分配变量并在it范围内使用它,因此必须在一个公共范围内声明该变量,在本例中就是describe范围。
补充道(适用于摩卡,但不适用于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);
});
});https://stackoverflow.com/questions/42318799
复制相似问题