简体   繁体   English

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

[英]How to mock fake url with axios for unit testing?

Context语境

The URL in this app is only accessible in production and it is not able to access via local.此应用中的 URL 只能在生产中访问,无法通过本地访问。 When doing unit tests, I need to mock the response of that url.在进行单元测试时,我需要模拟该 url 的响应。

What I got我得到了什么

Follow this tutorial按照本教程

Code I have我有的代码

saga.js传奇.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()]);
}

You can see that I made endpoint as const endpoint = 'http://sdfds';您可以看到我将端点设置为 const endpoint = 'http://sdfds'; , which is not accessible. ,这是不可访问的。

saga.test.js 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 axios.js

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

I was hopping this will overwrite the default axios我希望这会覆盖默认的axios

Full code here完整代码在这里

Summary概括

Need to overwrite default axios' return response.需要覆盖默认 axios 的返回响应。

In order to replace a module, you need to save your mock module in a specific folder structure: https://jestjs.io/docs/en/manual-mocks#mocking-node-modules为了替换模块,您需要将模拟模块保存在特定的文件夹结构中: https : //jestjs.io/docs/en/manual-mocks#mocking-node-modules

So it seems that in your project - https://github.com/kenpeter/test-saga/blob/master-fix/src/ tests /saga.test.js - you need to move the __mocks__ folder the root, where package.json is.如此看来,在您的项目- https://github.com/kenpeter/test-saga/blob/master-fix/src/测试/saga.test.js -你需要移动__mocks__文件夹的根目录,其中package.json是。 Then import axios normally like import mockAxios from 'axios' , and jest should take care of replacing the module.然后通常像import mockAxios from 'axios'一样import mockAxios from 'axios' ,并且 jest 应该负责替换模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM