CodePark/ questions / Mocks, spies & timers
START PRACTICINGPRACTICE
Frontend question · Testing › Mocks, spies & timers

./api is auto-mocked with jest.mock('./api'). The component calls fetchUser(id).then(setUser). Which line makes fetchUser resolve with Ana?

jest.mocked(fetchUser).mockResolvedValue({ name: 'Ana' })

mockResolvedValue(x) is short for returning Promise.resolve(x), so fetchUser resolves with Ana. The tempting mockReturnValue and mockImplementation options are wrong. They return a plain object, not a promise. A plain object has no .then, so the component throws. mockRejectedValue is wrong because it makes the promise reject.