如何用玩笑来模拟AxiosInstance

时间:2020-03-23 17:58:36

标签: node.js unit-testing jestjs axios

我想对使用axios将发布请求发送到另一台服务器的类进行单元测试,但我不断收到以下错误:

TypeError:无法读取未定义的属性“ post”

这是我的密码

//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;
  }
}

这就是我的测试结果:

//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();
  });
});

这可能是什么问题?任何帮助将不胜感激。

0 个答案:

没有答案