使用Jest时预期mock函数被调用一次,但实际上没有被调用

qoefvg9y  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(182)

我是Jest测试框架的新手,所以我不想太模仿一个返回Promise的函数来测试我的点击事件按钮。我收到一个错误,说我的方法还没有被调用,但是我在下面把它定义为jest.fn(),并希望它被调用一次。有什么帮助可以解决这个问题,或者澄清一下我的代码为什么是错误的。
第一个

zqdjd7g9

zqdjd7g91#

You have to pass your mocked method to the component you are rendering:

const markLessonFinished = jest.fn().mockResolvedValue(true)
const { getByText } = render(<ImmersivePage {...props} markLessonFinished={markLessonFinished} />)

At this point, I'm not sure how your component works but I'm assuming first you click the button and then the lesson is marked as finished. In this case, you would do:

fireEvent.click(getByLabelText('Next'))
await wait(()=> expect(markLessonFinished).toHaveBeenCalledTimes(1))

相关问题