簡體   English   中英

如何使用 axios 模擬假 url 進行單元測試?

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

語境

此應用中的 URL 只能在生產中訪問,無法通過本地訪問。 在進行單元測試時,我需要模擬該 url 的響應。

我得到了什么

按照本教程

我有的代碼

傳奇.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

完整代碼在這里

概括

需要覆蓋默認 axios 的返回響應。

為了替換模塊,您需要將模擬模塊保存在特定的文件夾結構中: https : //jestjs.io/docs/en/manual-mocks#mocking-node-modules

如此看來,在您的項目- https://github.com/kenpeter/test-saga/blob/master-fix/src/測試/saga.test.js -你需要移動__mocks__文件夾的根目錄,其中package.json是。 然后通常像import mockAxios from 'axios'一樣import mockAxios from 'axios' ,並且 jest 應該負責替換模塊。

暫無
暫無

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

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