0

I have following Node.js script.

const axios = require('axios');
const https = require('https');

const postRequest = (url, data) => {
  gLogger.debug('postRequest started');
  // try {
  const headers = {
    'Content-Type': 'application/json',
    'Content-Length': JSON.stringify(data).length,
  };

  const load = {
    headers,
    httpsAgent: agent,
  };

  gLogger.debug(`postRequest load: ${JSON.stringify(load)}`);

 const result = axios.post(url, data, load).then((response) => {
    return result;
  })
    .catch((error) => {
      return error;
    });
};

And this is for unit test:

const axios = require('axios');

const personalRecords = {
  data: { peopleDomain: { paom: { data: { persons: [], delta: 1, recordsFetched: 10 } } } },
};

const tockenData = {
  data: {
    access_token: 'access_token',
    expires_in: 1000,
  },
};
// jest.useFakeTimers();
jest.setTimeout(8000);

jest.mock('axios', () => ({
  post: jest.fn().mockReturnValue(tockenData),
  get: jest.fn().mockReturnValue(personalRecords),
  defaults: jest.fn().mockReturnValue(),
}));

The problem when I am running unit test yarn test, I keep getting the following error:

TypeError: axios.post(...).then is not a function.

What is the problem and how to fix it?

node_modules
  • 4,790
  • 6
  • 21
  • 37
R.Almoued
  • 219
  • 6
  • 16

1 Answers1

0

This is because you mock post function to be a function that returns a value instead of a promise. Remember post returns promise

This is the line that causes trouble:

post: jest.fn().mockReturnValue(tockenData),

To mock axios, there is an answer here:

How do I test axios in Jest?

Khoa
  • 2,632
  • 18
  • 13