首页 > 解决方案 > 开玩笑 mockResolvedValueOnce/mockReturnValueOnce 访问函数参数

问题描述

我想编写一个模拟函数,每次调用都会返回不同的值。我遇到的问题是返回值取决于传递给函数的参数值。

//something like this
window.fetch = jest.fn(urlPath)
                   .mockResolvedValueOnce(fetch({urlPath}))
                   .mockResolvedValueOnce(fetch({urlPath, arg1: 1}));

标签: jestjs

解决方案


使用模拟实现。它允许您传递一个函数并以细粒度的方式处理它。

jest.mockImplementation((arg1, arg2) => return whatever(arg1, arg2))


推荐阅读