首页 文章

如何使用酶ShallowWrapper在另一个React组件中找到存储为prop的React组件?

提问于
浏览
1

我有一个jest /酶测试,它在一个组件周围创建一个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放入触发器prop时,我收到错误,因为找不到#special-btn .

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

组件的酶快照显示Popup看起来像这样:

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

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

2 回答

  • 0

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

    (1)找到Popup并检查 trigger prop 's Button' s onClick prop是否 componentWrapper.instance().toggleShowThing

    (2)作为一个单独的东西,将 this.state.showThing 设置为false并验证没有具有className特殊事物的div;将 this.state.showThing 设置为true并验证它是否已呈现 .

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

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

相关问题