0

我正在编写一个react-redux应用程序,并且在我的一个动作创建者中,我正在通过axios

大致上,它看起来像这样:

import axios from 'axios'


export function getStoredData(userInput) {
    .
    .
    .

    var url = generateURL(userInput);

    var response = axios.get(url);

    return {
        type: GET_STORED_DATA
        payload: repsonse;
    };
}

我想使用axios-mock-adapter模拟 axios ,但我不太明白如何做到这一点,特别是因为我不想修改我的测试。action creator

请建议任何资源/指南来执行此操作...

4

2 回答 2

1

您可以使用依赖注入来交换 http 客户端,例如。

// your api module
var httpClient

export function getStoredData(userInput) {
    .
    .
    .

    var url = generateURL(userInput);

    var response = httpClient.get(url);

    return {
        type: GET_STORED_DATA
        payload: repsonse;
    };
}

export default function init(client) {
    httpClient = client
}

// init it when your program starts and the use it (should be a singleton instance in the app)
import Api, { getStoredData } from './api'
import axios from 'axios'
Api.init(axios)
getStoredData('user input')

//in your test
import Api, { getStoredData } from './api'
import axiosMock from 'axios-mock-adapter'
Api.init(axiosMock)
于 2017-08-12T21:57:18.467 回答
0
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import moxios from 'moxios';
import {
  submitRegistrationStepOneForm, // <-- this is an action that returns returns a promise
} from '../RegistrationActions';

const USER_ID = 999;
const USER_EMAIL = 'lucky_star@milkyway.test';
const userDataForStepOne = { email: USER_EMAIL };
const responseForUserRequest = { content: { id: USER_ID } };
const middlewares = [thunk];

const mockStore = configureStore(middlewares);

describe('Registration action tests for form', () => {
  beforeEach(() => moxios.install());
  afterEach(() => moxios.uninstall());

  it('submitRegistrationStepOneForm success should trigger correct dispatches', () => {
    const initialState = {};
    const store = mockStore(initialState);

    // simplest way is to use a regex to match url
    moxios.stubRequest(/users.*/, {
      status: 201,  // <-- you can replace this with a 5xx to test failure cases
      response: responseForUserRequest,
    });

    return store.dispatch(submitRegistrationStepOneForm({
      userData: userDataForStepOne,
    }))
      .then(() => {
        // in my case I used to run 2 dispatches on success call: 
        const actions = store.getActions();
        expect(actions.length).toEqual(2);
        expect(actions[0]).toEqual({ type: 'SUBMIT_REGISTRATION_FORM_DATA' });
        expect(actions[1]).toEqual({
          type: 'SUBMIT_REGISTRATION_STEP_ONE_SUCCESS',
          payload: { userId: USER_ID },
        });
        // ... more tests here if needed
      });
  });
  // ....

submitRegistrationStepOneForm 动作:

export const submitRegistrationStepOneForm = ({ userData, sourceArticle }) => {
  return (dispatch) => {
    dispatch(submitRegistrationDataAction());
    // signUpStepOne can be replaced directly with the axios promise
    return signUpStepOne({ userData })
      .then((body) => {
        const { content: { id } } = body;
        // ... some function calls and 2 dispatches here like:
        // dispatch(registrationSuccess({ userId: id }));
      })
      .catch((error) => {
        console.log('step one error', error); // eslint-disable-line
        dispatch(registrationFailureAction());
      });
  };
};
于 2018-06-13T14:51:42.843 回答