英文:
How We can mock test multiple api calls in jest testing
问题
我有一个情景,需要调用第一个API,然后根据第一个API的响应来调用第二个API。
我已经找到了测试第一个API的解决方案:
global.fetch = jest
.fn()
.mockImplementation(() => getMockPromise({ Response: resMock }));
我在模拟中获得了第一个响应,但如何获得第二个响应呢?我正在使用TypeScript和React。
我尝试在多个地方搜索,但只找到了用于Jest测试的一次模拟响应的解决方案,就像下面这样:
global.fetch = jest
.fn()
.mockImplementation(() => getMockPromise({ Response: resMock }));
我以为如果我使用上述的mockImplementation
两次来处理不同的响应,它会起作用,但仍然只有一个起作用。
英文:
I have a scenario like i have to call 1stAPI then depending on the response of 1st API i have to call 2nd API.
I got a solution to test 1st API :
global.fetch = jest
.fn()
.mockImplementation(() => getMockPromise({ Response: resMock }));
I got my 1st response while mocking
but how can I get response in second ? I am using typescript with react
I tried to search multiple places but only got solution for one mock response only for jest testing like below :
global.fetch = jest
.fn()
.mockImplementation(() => getMockPromise({ Response: resMock }));
I thought if I use the above mockImplementation
two times for different response it will work, but still same only one is working.
答案1
得分: 0
如果您每次调用 fetch()
时都使用不同的参数,可以使用模拟实现,根据接收到的参数返回不同的数据。
// 测试文件
const mockedResponses = {
'firstUrl': {}, // 第一个响应对象
'secondUrl': {}, // 第二个响应对象
}
global.fetch = jest
.fn()
.mockImplementation((url: string) => getMockPromise({ Response: mockedResponses[url] }));
通常,将实际的 fetch()
调用放在单独的函数内部是个好主意,例如 callFirstApi()
和 callSecondApi()
,然后您可以对这些函数进行模拟。这还意味着您不会覆盖全局函数。
您还可以查看类似 Nock 包这样的工具,它允许您对外部 API 进行更复杂的测试。
英文:
If you are calling fetch()
with different arguments each time, you can use a mock implementation that responds with different data depending on the argument it receives.
//test file
const mockedResponses = {
'firstUrl': {}, // first response object
'secondUrl': {}, // second response object
}
global.fetch = jest
.fn()
.mockImplementation((url: string) => getMockPromise({ Response: mockedResponses[url] }));
Generally it's a good idea to have the actual fetch()
call be done inside a separate function, e.g. callFirstApi()
and callSecondApi()
, and then you can just mock those functions instead. This also means you don't end up overwriting a global function.
You can also look into something like the Nock package which lets you do more elaborate testing of external APIs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论