【问题标题】:How to test callback argument react native如何测试回调参数反应原生
【发布时间】:2018-09-24 08:24:17
【问题描述】:

我有一个看起来像这样的原生组件:

export class Estimate extends PureComponent {
  setRef =
    (ref) => {
      this.estimateForm = ref
    }

  render () {
    const { onPress } = this.props
    return (
      <Form
        name="estimateForm"
        ref={this.setRef}
      >
        <Actions style={{ alignItems: 'flex-end' }}>
          <Button
            type="text"
            style={{ marginBottom: -em(0.5) }}
            onPress={() => onPress(this.estimateForm.values)}
            title={t('estimateShippingAndTax')}
          />
          <TextInput
            placeholder={t('postalCode')}
            name="estimate"
            style={{ width: 100 }}
            validate="postalCode"
          />
        </Actions>
      </Form>
    )
  }
}

我的笑话/酶测试看起来像:

let obj
let onPressFunction
describe('Estimate', () => {
  beforeAll(() => {
    onPressFunction = jest.fn()
    obj = shallow(<Estimate onPress={onPressFunction} />)
  })

  test('Text gets returned with onPress', () => {
    console.log(obj.html())
    const value = { values: { estimate: '61606' } }
    obj.instance().setRef(value)
    obj.find('Button').first().simulate('onPress')
    expect(onPressFunction).toHaveBeenCalledWith('61606')
  })
})

即使我的组件按预期工作,我似乎也无法通过测试。我的测试失败了:

预期的模拟函数已被调用: [“61606”] 但它没有被调用。

【问题讨论】:

  • 我正在传递整个有效负载,因为我还没有向表单添加更多元素

标签: javascript reactjs react-native jestjs enzyme


【解决方案1】:

您的酶测试应该模拟press 事件,而不是onPress 事件。事件名称为“press”。

obj.find('Button').first().simulate('press')

看你的标签,这是一个 React Native 项目,this thread on the Enzyme repo 建议尝试直接调用方法而不是依赖simulate

obj.find('Button').first().props().onPress()

【讨论】:

  • 谢谢 :)
猜你喜欢
  • 2016-09-09
  • 2016-09-24
  • 2016-04-10
  • 2017-04-14
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
相关资源
最近更新 更多