javascript - 如何使用 axios 模拟虚假 url 进行单元测试?

标签 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()]);
}

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

最佳答案

为了替换模块,您需要将模拟模块保存在特定的文件夹结构中: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 所在的位置。然后正常导入 axios,就像 import mockAxios from 'axios' 一样,jest 应该负责替换模块。

关于javascript - 如何使用 axios 模拟虚假 url 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59167657/

相关文章:

javascript - 如何在 javascript 装饰器中使用 Angular2 依赖注入(inject)?

javascript - CSS在Chrome中申请代码,在Firefox和IE中申请不到?

javascript - 样式组件和 Webpack 5 联合模块之间的冲突(无效的钩子(Hook)调用)

javascript - React 中方括号解构的概念理解

unit-testing - 带图的 TDD

javascript - 阻止移动网页上的设备旋转

javascript - 使用 console.log(object) 并迭代对象键时 JSON 键不同

reactjs - React props 在调用 setState 之前发生变化 (react-beautiful-dnd)

visual-studio-2010 - Resharper - 在构建时运行 NUnit 单元测试

c# - 如何使用 moq 框架在 c# 中为私有(private)方法编写单元测试?