【问题标题】:How to mock fake url with axios for unit testing?如何使用 axios 模拟假网址进行单元测试?
【发布时间】:2020-03-28 18:17:39
【问题描述】:

上下文

此应用中的 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()]);
}

您可以看到我将端点设置为 const 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 的返回响应。

【问题讨论】:

标签: javascript reactjs unit-testing axios


【解决方案1】:

要替换模块,您需要将模拟模块保存在特定的文件夹结构中: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,jest应该注意替换模块。

【讨论】:

    猜你喜欢
    • 2015-03-25
    • 1970-01-01
    • 2018-04-04
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    相关资源
    最近更新 更多