kamlesh.bar
kamlesh.bar

Reputation: 1804

How to mock multiple axios call with jest?

Within my Typescript handler I have multiple axios call as follows

export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
const options = {
   headers: {
      Accept: 'application/json',
     'Content-Type': 'application/json;charset=UTF-8',
     authorization: 'Token',
   },
 }; 
    const respData = await axios
    .all([
      axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5', options),
      axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5', options)
    ])
    .then(axios.spread((todos, posts) => {todos, posts}))
    .catch(err => console.error(err));

  return {
     statusCode: 200,
     body: JSON.stringify(respData),
  };

};

How to mock those multiple API calls with jest ?

Upvotes: 0

Views: 1662

Answers (1)

Lin Du
Lin Du

Reputation: 102207

You can use jest.spyOn(object, methodName) and mockFn.mockImplementation(fn) to mock axios.get() method with different resolved value based on url parameter.

Besides, from the doc Concurrency (Deprecated), we know axios.all() and axios.spread() methods are deprecated. Use Promise.all to replace them.

main.ts:

import axios from 'axios';

interface APIGatewayProxyEvent {}
interface APIGatewayProxyResult {}

export const handler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
  const options = {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json;charset=UTF-8',
      authorization: 'Token',
    },
  };
  const respData = await axios
    .all([
      axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5', options),
      axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5', options),
    ])
    .then(axios.spread((todos, posts) => ({ todos, posts })))
    .catch((err) => console.error(err));

  return { statusCode: 200, body: JSON.stringify(respData) };
};

main.test.ts:

import { handler } from './main';
import axios from 'axios';

describe('69096350', () => {
  test('should pass', async () => {
    const axiosGetSpy = jest.spyOn(axios, 'get').mockImplementation(async (url) => {
      if (url === 'https://jsonplaceholder.typicode.com/todos?_limit=5') {
        return [1, 2, 3, 4, 5];
      } else if (url === 'https://jsonplaceholder.typicode.com/posts?_limit=5') {
        return ['a', 'b', 'c', 'd', 'e'];
      }
    });
    const actual = await handler({});
    expect(actual).toEqual({
      statusCode: 200,
      body: JSON.stringify({ todos: [1, 2, 3, 4, 5], posts: ['a', 'b', 'c', 'd', 'e'] }),
    });
    expect(axiosGetSpy).toBeCalledWith('https://jsonplaceholder.typicode.com/todos?_limit=5', {
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json;charset=UTF-8',
        authorization: 'Token',
      },
    });
    expect(axiosGetSpy).toBeCalledWith('https://jsonplaceholder.typicode.com/posts?_limit=5', {
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json;charset=UTF-8',
        authorization: 'Token',
      },
    });
    axiosGetSpy.mockRestore();
  });
});

test result:

 PASS  examples/69096350/main.test.ts (7.535 s)
  69096350
    ✓ should pass (4 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   88.89 |      100 |      75 |   85.71 |                   
 main.ts  |   88.89 |      100 |      75 |   85.71 | 20                
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        8.035 s, estimated 9 s
Ran all test suites related to changed files.

Upvotes: 1

Related Questions