React & Enzyme:为什么 beforeEach() 不起作用?

React & Enzyme: why isn't beforeEach() working?

我正在编写我的第一个 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 范围内定义包装器常量,像这样将它移到外部:

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);
  });
});

这样您就可以访问 its 范围内的包装器。

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 范围内使用它,你必须在公共范围内声明变量,其中,这种情况是 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);
  });
});