Jitender
Jitender

Reputation: 7969

Jest mocking axios's request method giving error

I am trying to mock the axios's request method. But it throwing error

it('should execute axios request method once', async () => {
  jest.mock('axios');
  axios.request.mockImplementation(() =>
    Promise.resolve({
      data: {}
    })
  );
  const requestObj = {
    method: 'GET',
    url: 'http://mock.url',
    headers: {}
  };
  await request(requestObj);
  expect(axios.request).toHaveBeenCalledTimes(1);
});

request.js

export default async (request, httpService = axios) => {
  const { method, data, headers } = request;
  let { url } = request;
  const token = getLocalstorage('token');
  if (token) {
    headers.token = token;
  }
  if (method === 'GET') {
    if (data) {
      url += `?${serialize(data)}`;
    }
  }
  return httpService
    .request({
      method,
      url,
      headers: Object.assign({}, headers),
      ...(method !== 'GET' && { data })
    })
    .then(successResponse, error => {
      throwHttpError(error);
    });
};

error enter image description here

Upvotes: 0

Views: 449

Answers (1)

Lin Du
Lin Du

Reputation: 102607

Here is the solution based on:

"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"
"axios": "^0.19.0",

request.ts:

import axios from 'axios';
const serialize = data => data;
const getLocalstorage = key => key;
const successResponse = () => console.log('successResponse');
const throwHttpError = error => new Error(error);

export default async (request, httpService = axios) => {
  const { method, data, headers } = request;
  let { url } = request;
  const token = getLocalstorage('token');
  if (token) {
    headers.token = token;
  }
  if (method === 'GET') {
    if (data) {
      url += `?${serialize(data)}`;
    }
  }

  return httpService
    .request({
      method,
      url,
      headers: Object.assign({}, headers),
      ...(method !== 'GET' && { data })
    })
    .then(successResponse, error => {
      throwHttpError(error);
    });
};

Unit test, request.spec.ts

import request from './request';
import axios from 'axios';

jest.mock('axios');

describe('request', () => {
  it('should execute axios request method once', async () => {
    (axios.request as jest.Mock<any, any>).mockResolvedValueOnce({ data: 'mocked data' });
    const requestObj = {
      method: 'GET',
      url: 'http://mock.url',
      headers: {}
    };
    await request(requestObj);
    expect(axios.request).toHaveBeenCalledTimes(1);
  });
});

Unit test result:

 PASS  src/stackoverflow/57353897/request.spec.ts
  request
    ✓ should execute axios request method once (13ms)

  console.log src/stackoverflow/57353897/request.ts:4
    successResponse

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.637s, estimated 3s

Upvotes: 1

Related Questions