我正在尝试在 React 项目中掌握测试组件的窍门。到目前为止,我在单个组件上有一个测试文件,我正在尝试将此文件准备为包含多个测试的测试套件。import React from 'react';import Enzyme, { mount } from 'enzyme';import Adapter from 'enzyme-adapter-react-16';import HamburgerIcon from './HamburgerIcon';Enzyme.configure({ adapter: new Adapter() });describe('<HamburgerIcon />', () => { const hamburgerIcon = mount(<HamburgerIcon showOverlay={showOverlay} />); it('displays on mobile', () => { ... ... }); it('has class .open after click', () => { ... ... }); hamburgerIcon.unmount();});我已经删除了两个测试的内容,但基本上这两个测试都包含在一个describe函数中,并且我正在尝试mount使用一次组件和unmount一次组件以保持干燥(不要重复自己) .我mount将两个it函数放在之前,认为在运行测试之前安装组件是合乎逻辑的。我unmount在两个测试函数之后放置了,这导致了错误:方法“模拟”旨在在 1 个节点上运行。0 找到了。我认为这是因为在实际运行测试之前组件正在卸载。如果我mount和unmount在这两个测试中,像这样......describe('<HamburgerIcon />', () => { it('displays on mobile', () => { const hamburgerIcon = mount(<HamburgerIcon showOverlay={showOverlay} />); ... ... hamburgerIcon.unmount(); }); it('has class .open after click', () => { const hamburgerIcon = mount(<HamburgerIcon showOverlay={showOverlay} />); ... ... hamburgerIcon.unmount(); });});...测试通过。不过,这似乎有些过分。如果我的测试套件有十个测试功能呢?我应该在每次测试时都像这样安装和卸载吗?
1 回答

婷婷同学_
TA贡献1844条经验 获得超8个赞
您可以使用 beforeEach 和 afterEach 函数来设置和清除您的测试。
afterEach(() => {
//do the unmounting and other stuff here
//this will be called after each test case
});
beforeEach(() => {
//do the mounting and setting up the test case here
//this will be called before each test case
});
添加回答
举报
0/150
提交
取消