使用 Jest 监视链式方法调用不起作用

IT技术 javascript reactjs react-native jestjs
2021-05-03 04:27:44

我制作了我自己的TextInput带有nextFieldprops的自定义组件TextInput按下my 中的“完成”按钮时nextField应该聚焦。很简单。它在生产中工作。

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

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

我正在使用这个间谍测试它:

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

我的理解是,当被测代码行被触发时,我应该看到nextFieldSpy并且nextFieldSpy().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)

这是怎么回事?

1个回答

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

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

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