PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to use Typescript, Jest and Axios to mock two different requests in the same unit test?

 October 13, 2022     axios, javascript, ts-jest, typescript, unit-testing     No comments   

Issue

So I have function A and function B

function A does a GET request

function B does a GET request

function B is inside function A

I want to test the function A, and in order to do that I need to mock two GET requests(one mock for each function) to different endpoints with different responses. How can I do that using Jest and Axios?

I couldn't figure out how to mock the second call:

it("test", async () => {
    mock.get.mockResolvedValue({ data: RESPONSE });

    const response = await functionA(input);

    expect(response).toMatchObject({ status: 1 });
    expect(response.value).toMatchObject({
      state: { status: "OK" },
      data: RESPONSE,
    });
  });

Solution

This solved my problem:

mock.get.mockImplementation((url) => {
      switch (url) {
        case 'URL_A':
          return Promise.resolve({data: data_A})
        case 'URL_B':
          return Promise.resolve({data: data_B})
        default:
          return Promise.reject(new Error('error message'))
      }
    })


Answered By - mattdonsk
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing