【问题标题】:Spying on chained method calls with Jest not working用 Jest 监视链式方法调用不起作用
【发布时间】:2018-08-16 03:55:55
【问题描述】:

我已经制作了自己的自定义 TextInput 组件,该组件采用 nextField 属性。当我的TextInput 中的“完成”按钮被按下时,nextField 应该被聚焦。很简单。它在生产中工作。

但是,我在测试关注 nextField 的代码行时遇到了问题:

this.props.nextField && this.props.nextField().focus()

我正在使用这个间谍对其进行测试:

const nextFieldSpy = jest.fn(() => {return {focus: jest.fn()}})

据我了解,当被测代码行被触发时,我应该看到nextFieldSpynextFieldSpy().focus都被调用了。

但是,事实并非如此。以下是 Jest 的期望:

expect(nextFieldSpy).toHaveBeenCalledTimes(1) expect(nextFieldSpy().focus).toHaveBeenCalledTimes(1)

这就是我得到的错误——第一行通过,但第二行失败。

 Expected mock function to have been called one time, but it was called zero times.

  72 |     expect(nextFieldSpy).toHaveBeenCalledTimes(1)
> 73 |     expect(nextFieldSpy().focus).toHaveBeenCalledTimes(1)

发生了什么事?

【问题讨论】:

    标签: javascript reactjs react-native jestjs


    【解决方案1】:

    nextFieldSpy() 每次调用都会返回一个新对象。

    更改创建 nextFieldSpy 的方式以始终返回相同的对象:

    const nextFieldResult = {focus: jest.fn()};
    const nextFieldSpy = jest.fn(() => nextFieldResult);
    

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 1970-01-01
      • 2015-08-25
      • 2019-03-31
      • 2018-12-07
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      相关资源
      最近更新 更多