问题描述
我已经制作了自己的自定义TextInput
组件,该组件带有nextField
道具.当按下我的TextInput
中的完成"按钮时,应将nextField
对准焦点.很简单它可以在生产中使用.
I've made my own custom TextInput
component that takes a nextField
prop. When the "done" button in my TextInput
is pressed, the nextField
should be focused. Pretty simple. It works in production.
但是,我在测试聚焦nextField
的代码行时遇到了麻烦:
However, I'm having trouble testing the line of code that focuses nextField
:
this.props.nextField && this.props.nextField().focus()
我正在使用此间谍对其进行测试:
I'm testing it using this spy:
const nextFieldSpy = jest.fn(() => {return {focus: jest.fn()}})
据我了解,当触发测试中的代码行时,我应该看到同时调用了nextFieldSpy
和nextFieldSpy().focus
.
It's my understanding that when the line of code under test is triggered, I should see that nextFieldSpy
and nextFieldSpy().focus
have both been called.
但是,事实并非如此.这是开玩笑的期望:
However, this is not the case. Here are the Jest expectations:
expect(nextFieldSpy).toHaveBeenCalledTimes(1)
expect(nextFieldSpy().focus).toHaveBeenCalledTimes(1)
这是我得到的错误-第一行通过,但第二行失败.
And this is the error I'm getting––the first line passes, but the second fails.
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)
这是怎么回事?
推荐答案
nextFieldSpy()
每次调用时都会返回一个新对象.
nextFieldSpy()
returns a new object every time it is called.
更改创建nextFieldSpy
的方式以始终返回同一对象:
Change how you create nextFieldSpy
to always return the same object:
const nextFieldResult = {focus: jest.fn()};
const nextFieldSpy = jest.fn(() => nextFieldResult);
这篇关于在Jest不起作用的情况下监视链接方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!