Spying on chained method calls with Jest not worki

2019-08-09 08:06发布

问题:

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.

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()}})

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)

What's going on?

回答1:

nextFieldSpy() returns a new object every time it is called.

Change how you create nextFieldSpy to always return the same object:

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