【问题标题】:How to add new test for onClick function using enzyme?如何使用酶为 onClick 功能添加新测试?
【发布时间】:2020-11-16 19:06:45
【问题描述】:

我想根据条件编写测试用例,我想检查 onClick 功能

检查条件

  1. 当 props.item1 为 true 而 props.item2 为 false 时
  2. 当 props.item1 为 false 而 props.item2 为 true 时
  3. 当 props.item1 为真且 props.item2 为真时
  4. 当 props.item1 为 false 而 props.item2 为 false 时

我想知道如何使用这种条件检查 onClick 函数

这里的onclick是一个void类型的函数(onclick():void)

<Container>
  <span onClick={props.onClick || undefined}>{props.item}</span>
    { props.item1 && !props.item2 && (
      <span onClick={props.onClick || undefined}>Edit</span>
    )}
</Container>

这是测试用例

describe('item list tests', () => {
  const props = {
  item: 'abc',
  item1: true,
  item2: false,
  onClick: () => jest.fn(),
}

test('prop values',() => {
  const output = shallow(<Header {...props} />)
  expect(output.find(Container).find('span')).toHaveLength(2)
  expect(output.find(Container).props().item1).toBe(true)
  expect(output.find(Container).props().item2).toBe(false)
 })
})

错误

 expect(output.find(Container).props().onClick).toBeCalled() //received value must be a mock or spy function

还有哪些其他的测试用例可以在这里添加。对于上述容器组件

【问题讨论】:

  • 我认为需要更多的上下文/背景来考虑更多的测试用例。关于错误,您必须模拟 onClick 函数,但我不确定您是否要解决该问题。
  • @Rahul ,是的,我也想模拟点击功能,对此有点困惑。那么对于特定的容器,我可以添加哪些测试用例?这就是问题
  • 您能否更全面地了解您想要做什么?也许我可以帮助你更好的代码设计。
  • 当然,基本上我需要要测试的容器我有一个函数 onClick,它是 Void 类型,所以在我的道具对象中我将它设置为 onClick: () => jest.fn(),现在我想要测试容器组件的可能方法
  • 使测试容器组件的测试用例变得更简单

标签: reactjs jestjs enzyme


【解决方案1】:

由于我无法获得更大的图景,我只能根据给定的信息提出这么多的建议。

  1. 例如,您可以执行类似的操作来检查跨度是否基于道具呈现。

    expect(wrapper.find({ id: 'element-id' }).exists()).toBeTruthy()

  2. 如果你想执行一个点击动作并根据标题的一些内部状态逻辑检查它的结果。你可以在测试用例中做这样的事情

    props.onClick()
    
    
    //then check if the component is rendered or hidden
    expect(wrapper.find({ id: 'hidden-element' }).exists()).toBe(false)
    

【讨论】:

    猜你喜欢
    • 2019-04-24
    • 2020-09-14
    • 2017-04-11
    • 2020-11-17
    • 2020-09-21
    • 2021-02-09
    • 2021-07-27
    • 2018-12-18
    • 2020-02-25
    相关资源
    最近更新 更多