2

I want to unit test a class which use axios to send post request to another server but I keep getting the following error:

TypeError: Cannot read property 'post' of undefined

Here are my codes

//PostController.ts
const axios = require('axios').default;

export class PostController {
  async sendPostRequest(): Promise<boolean> {
    //type AxiosInstance
    const instance = axios.create({
      baseURL: 'http://example.com',
      timeout: 60 * 3 * 1000, //milliseconds. 3 minutes. 
      headers: {'X-Custom-Header': 'secret-key'}
    });

    const {status} = await instance.post('/submitUsername', {username: 'nux'});

    return status === 200;
  }
}

And this is how my test look like:

//PostController.test.ts
import {PostController} from './ProviderController';
import axios from 'axios';

const mockedAxios = axios as jest.Mocked<typeof axios>;

jest.mock('axios');

describe('PostController', () => {
  it('should send post request and return 200', async () => {
    const controller = new PostController();
    const response = {status: 200};

    mockedAxios.post.mockResolvedValue(response);
    const result = await controller.sendPostRequest();

    expect(mockedAxios.post).toHaveBeenCalled();
    expect(result).toBeTruthy();
  });
});

What could be wrong here? Any help will be appreciated.

Nux
  • 5,890
  • 13
  • 48
  • 74

0 Answers0