簡體   English   中英

如何測試 axios 包裝

[英]How to test axios wrapper

我不知道如何測試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;

我還使用此 function 創建了具體的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 };

如何在client.js中測試logIn()和其他功能? 特別是,我想知道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 });
  });
});

您可以使用jest.mock(moduleName, factory, options)模擬./createApiClient模塊、 createApiClient function 及其返回值。

例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM