Enzyme Mount/Shallow once on before hook on 摩卡

Enzyme Mount/Shallow once on before hook on Mocha

每个测试用例我都有 mount/shallow 组件,我发现这是多余的。在 before 挂钩上安装一次是个好主意吗?或者我以后可能会遇到一些问题,尤其是当我要在我的组件上设置状态或道具时?

例如:

import React from 'react';
import {mount,shallow} from 'enzyme';
import {expect} from 'chai';
import ScheduleApp from '../src/components/schedule-app.jsx';
import ScheduleForm from '../src/components/schedule-form.jsx';
import ScheduleTable from '../src/components/schedule-result-table.jsx';

describe('<ScheduleApp/>', function() {
  describe('Initial Mount', function() {
    let wrapper;

    before(function() {
      wrapper = mount(<ScheduleApp />);
    });

    it('contains 1 <ScheduleForm/> component', function() {
      expect(wrapper.find(ScheduleForm)).to.have.length(1);
    });

    it('contains 1 <ScheduleTable/> component', function() {
      expect(wrapper.find(ScheduleTable)).to.have.length(1);
    });
  });
});

如果您不打算使用不同的 props 测试 Schedule App,则无需为每个案例安装它。

您也不需要导入子组件(ScheduleForm 和 ScheduleTable)来告诉酶找到它们。 Enzyme finds child components by their display name.

您可以将上面的代码重构为

import React from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import ScheduleApp from '../src/components/schedule-app.jsx';

describe('<ScheduleApp/>', function() {
  describe('Initial Mount', function() {
    const wrapper = mount(<ScheduleApp />);

    it('contains 1 <ScheduleForm /> component', function() {
      expect(wrapper.find('ScheduleForm')).to.have.length(1);
    });

    it('contains 1 <ScheduleTable /> component', function() {
      expect(wrapper.find('ScheduleTable')).to.have.length(1);
    });
  });
});