我正在编写我的第一个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范围内的包装器。



由于要在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:为什么beforeEach()不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42318799/

10-10 00:25