【问题标题】:How to test axios wrapper如何测试 axios 包装器
【发布时间】:2020-08-26 00:21:19
【问题描述】:

我不知道如何测试axios 包装函数。我应该模拟什么?

我有createApiClient.js 文件:

import createApiClient from '../createApiClient';

import axios from 'axios';

function createApiClient(config = {}) {
  const client = axios.create(config);
  client.interceptors.response.use((response) => response.data,
    (error) => {
      if (error.response) {
        throw error.response.data;
      } else {
        throw new Error('Ошибка во время соединения с сервером! Попробуйте повторить попытку позже.');
      }
    });
  return client;
}
export default createApiClient;

我还使用此函数创建了具体的client.js 文件:

import createApiClient from '../createApiClient';

const request = createApiClient({
  baseURL: process.env.VUE_APP_AUTH_API_URL,
});
async function logIn(username, password) {
  const { token } = await request.post('login/', {
    username,
    password,
  });
  return token;
}
// other functions...
export { logIn, register, getUserInfo };

如何测试logIn()client.js中的其他功能?特别是,我想知道axios.create()interceptors等。

我尝试了这个和一些变化:

import createApiClient from '@/api/createApiClient';
import { logIn } from '@/api/auth/client';

const token = 'token';
describe('Тестирование API аутентификации', () => {
  test('log in success', async () => {
    const request = createApiClient();
    request.post = jest.fn(() => Promise.resolve(token));
    const response = await logIn('foo', 'qwerty');
    response.toBe({ token });
  });
});

【问题讨论】:

    标签: javascript api unit-testing jestjs axios


    【解决方案1】:

    您可以使用jest.mock(moduleName, factory, options) 模拟./createApiClient 模块、createApiClient 函数及其返回值。

    例如

    client.js:

    import createApiClient from './createApiClient';
    
    const request = createApiClient({
      baseURL: process.env.VUE_APP_AUTH_API_URL,
    });
    
    async function logIn(username, password) {
      const { token } = await request.post('login/', {
        username,
        password,
      });
      return token;
    }
    
    export { logIn };
    

    createApiClient.js:

    import axios from 'axios';
    
    function createApiClient(config = {}) {
      const client = axios.create(config);
      client.interceptors.response.use(
        (response) => response.data,
        (error) => {
          if (error.response) {
            throw error.response.data;
          } else {
            throw new Error('Ошибка во время соединения с сервером! Попробуйте повторить попытку позже.');
          }
        },
      );
      return client;
    }
    
    export default createApiClient;
    

    client.test.js:

    import { logIn } from './client';
    import createApiClientMock from './createApiClient';
    
    jest.mock('./createApiClient', () => {
      const axiosInstance = { post: jest.fn() };
      return jest.fn(() => axiosInstance);
    });
    
    describe('61713112', () => {
      it('should pass', async () => {
        const axiosInstanceMock = createApiClientMock();
        const mResponse = { token: 'token' };
        axiosInstanceMock.post.mockResolvedValueOnce(mResponse);
        const actual = await logIn('foo', 'qwerty');
        expect(actual).toEqual('token');
        expect(axiosInstanceMock.post).toBeCalledWith('login/', { username: 'foo', password: 'qwerty' });
      });
    });
    

    带有覆盖率报告的单元测试结果:

     PASS  stackoverflow/61713112/client.test.js
      61713112
        ✓ should pass (4ms)
    
    -----------|---------|----------|---------|---------|-------------------
    File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    -----------|---------|----------|---------|---------|-------------------
    All files  |     100 |      100 |     100 |     100 |                   
     client.js |     100 |      100 |     100 |     100 |                   
    -----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        4.582s, estimated 20s
    

    【讨论】:

    • 哇,非常感谢。这一天我一直在琢磨。
    猜你喜欢
    • 2014-03-22
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 2019-04-28
    • 2017-08-27
    • 1970-01-01
    相关资源
    最近更新 更多