使用axios构造函数时模拟axios [英] Mock axios when using the axios constuctor function

查看:83
本文介绍了使用axios构造函数时模拟axios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API实用程序函数,该函数使用构造函数表示法调用axios:

I have an API utility function that calls axios using the constructor notation:

axios({
   method,
   url: `${BASE_URL}/${url}`,
   data
});

我想用Jest模拟这个,但不太确定如何.我只能模拟特定的axios函数(获取,发布等).

I want to mock this using Jest, but not quite sure how. I was only able to mock a specific axios function (get, post, etc.).

有人使用这种方式模仿axios的例子吗?

Does anyone have an example of mocking axios when using it this way?

推荐答案

您可以使用

You can use jest.mock(moduleName, factory, options) to mock axios function.

例如

index.js:

import axios from 'axios';

export function main() {
  const BASE_URL = 'https://stackoverflow.com';
  const url = 'api';
  const data = {};
  return axios({
    method: 'GET',
    url: `${BASE_URL}/${url}`,
    data,
  });
}

index.test.js:

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

jest.mock('axios', () => jest.fn());

describe('59873406', () => {
  it('should pass', async () => {
    const mResponse = { data: 'mock data' };
    axios.mockResolvedValueOnce(mResponse);
    const response = await main();
    expect(response).toEqual(mResponse);
    expect(axios).toBeCalledWith({ method: 'GET', url: 'https://stackoverflow.com/api', data: {} });
  });
});

单元测试结果覆盖率100%:

Unit test results with 100% coverage:

 PASS  src/stackoverflow/59873406/index.test.js
  59873406
    ✓ should pass (7ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.js |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.362s, estimated 13s

源代码: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59873406

这篇关于使用axios构造函数时模拟axios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆