如何使用axios模拟假URL以进行单元测试?

时间:2019-12-04 01:20:21

标签: javascript reactjs unit-testing axios

上下文

此应用程序中的URL仅可在生产环境中访问,并且无法通过本地访问。在进行单元测试时,我需要模拟该URL的响应。

我得到的

关注此tutorial

我有验证码

saga.js

import {all, call, put, takeEvery} from 'redux-saga/effects';
import axios from 'axios';

async function myfetch(endpoint) {
  const out = await axios.get(endpoint);
  return out.data;
}

function* getItems() {
  //const endpoint = 'https://jsonplaceholder.typicode.com/todos/1';
  const endpoint = 'http://sdfds';
  const response = yield call(myfetch, endpoint);
  const items = response;

  //test
  console.log('items', items);

  yield put({type: 'ITEMS_GET_SUCCESS', items: items});
}

export function* getItemsSaga() {
  yield takeEvery('ITEMS_GET', getItems);
}

export default function* rootSaga() {
  yield all([getItemsSaga()]);
}

您会看到我将端点设置为常量endpoint = 'http://sdfds';,这是不可访问的。

saga.test.js

// Follow this tutorial: https://medium.com/@lucaspenzeymoog/mocking-api-requests-with-jest-452ca2a8c7d7
import SagaTester from 'redux-saga-tester';
import mockAxios from 'axios';
import reducer from '../reducer';
import {getItemsSaga} from '../saga';

const initialState = {
  reducer: {
    loading: true,
    items: []
  }
};

const options = {onError: console.error.bind(console)};

describe('Saga', () => {
  beforeEach(() => {
    mockAxios.get.mockImplementationOnce(() => Promise.resolve({key: 'val'}));
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('Showcases the tester API', async () => {
    const sagaTester = new SagaTester({
      initialState,
      reducers: {reducer: reducer},
      middlewares: [],
      options
    });

    sagaTester.start(getItemsSaga);

    sagaTester.dispatch({type: 'ITEMS_GET'});

    await sagaTester.waitFor('ITEMS_GET_SUCCESS');

    expect(sagaTester.getState()).toEqual({key: 'val'});
  });
});

axios.js

const axios = {
  get: jest.fn(() => Promise.resolve({data: {}}))
};
export default axios;

我当时希望这会覆盖默认的axios

Full code here

摘要

需要覆盖默认axios的返回响应。

1 个答案:

答案 0 :(得分:0)

要替换模块,您需要将模拟模块保存在特定的文件夹结构中:https://jestjs.io/docs/en/manual-mocks#mocking-node-modules

看来,在您的项目https://github.com/kenpeter/test-saga/blob/master-fix/src/tests/saga.test.js中,您需要将__mocks__文件夹移到package.json所在的根目录下。然后通常像import mockAxios from 'axios'一样导入axios,开玩笑应该注意更换模块。