如何在Jest测试中模拟多个API调用

huangapple go评论68阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月18日 01:43:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定