2

我有一个 jest/enzyme 测试,它在组件周围创建一个 ShallowWrapper,找到一个指定的语义-ui-react 按钮(通过 id),模拟按钮上的点击,然后查看点击是否切换了某些内容。

示例 JSX:

<Popup
  trigger={<Button onClick={this.toggleShowThing} id="special-btn">a button</Button>}
  content="Popup Words"
/>
{this.state.showThing &&
  <div className="special-thing">The Thing's Words</div>
}

样品测试:

it('shows the thing when the button is clicked', () => {
  const wrapper = shallow(<MyComponent />);
  wrapper.find('#special-btn').simulate('click', { preventDefault() {} });
  expect(wrapper.find('.special-thing').exists()).toBe(true);
});

当我刚刚拥有 Button 时,此测试有效。当我添加 Popup 并将 Button 放入 trigger 道具时,我收到一个错误,因为找不到#special-btn。

错误:方法“props”仅用于在单个节点上运行。找到了 0 个。

该组件的酶快照显示弹出窗口如下所示:

<Popup 
  content="Popup Words"
  on="hover"
  position="top left"
  trigger={
    <Button
      id="special-btn"
      onClick={[Function]}
    >
      a button
    </Button>
  }
/>

我需要我的测试才能再次工作。如何在测试中再次获得对 #special-btn 的访问权限,以便可以调用 .simulate('click') ?

4

3 回答 3

2

这对我有用,尽管没有文档:

import {shallow, ShallowWrapper} from "enzyme";

it('shows the thing when the button is clicked', () => {
  const wrapper = shallow(<MyComponent />);
  const button = new ShallowWrapper(
    wrapper.find('Popup').prop('trigger'), wrapper
  );
  button.simulate('click', { preventDefault() {} });
  expect(wrapper.find('.special-thing').exists()).toBe(true);
});

换句话说:

  1. 找到Popup组件。
  2. 获取在其triggerprop 中呈现的组件。请注意,这还不是一个浅包装,所以还没有花哨的 API。
  3. 使用手动创建包装器ShallowWrapper(传递第二个参数很重要)。
  4. 现在您可以访问所有酶 API 以与按钮进行交互。

请注意,您似乎可以避免使用构造函数并改用wrap()实用程序方法(也未记录):

  const button = wrapper.wrap(wrapper.find('Popup').prop('trigger'));
于 2020-03-18T15:07:02.843 回答
1

假设 Popup 是一些已经过测试的第三方组件,我将通过以下方式进行测试:

(1)找到Popup,检查triggerprop的Button的onClickprop是否为componentWrapper.instance().toggleShowThing

(2) 作为一个单独的东西,设置this.state.showThing为false并验证没有className的div被渲染;设置this.state.showThing为 true 并验证它是否被渲染。

(*)this.toggleShowThing也应自行测试。

于 2017-08-23T22:43:19.163 回答
0

问题是你做不到。你需要重写你的测试。您的按钮现在被一个Popup组件包裹,因此您无权访问它。但是您可以将选择器移动到Popup并测试单击弹出窗口是否触发需要更改。没有其他办法了。

// JSX
<Popup
  trigger={<Button onClick={this.toggleShowThing} id="special-btn">a button</Button>}
  content="Popup Words"
  id="popup"
/>
{this.state.showThing &&
  <div className="special-thing">The Thing's Words</div>
}

// test
it('shows the thing when the button is clicked', () => {
  const wrapper = shallow(<MyComponent />);
  wrapper.find('#popup').simulate('click', { preventDefault() {} });
  expect(wrapper.find('.special-thing').exists()).toBe(true);
});
于 2017-08-23T22:17:31.097 回答