-2
import service from "Api/service";
import { ROOT_URL, saveError } from "Api";
import {
  FETCH_USER_REQUEST,
  FETCH_USER_FAILURE,
  FETCH_USER_SUCCESS
} from "Constants/redux";
// it fetch the details of an user
export const fetchDetails = () => {
  return (dispatch, getState) => {
    dispatch(fetchDetailsRequest());
    return service
      .get(`${ROOT_URL}/employees/list`)
      .then(response => {
         dispatch(fetchDetailsSuccess(response));
      })
      .catch(error => {
        console.log(error);
        saveError(error, getState());
        dispatch(fetchDetailsFailure(error));
      });
  };
};

export const ffetchDetailsRequest = () => {
  return {
    type:  FETCH_USER_REQUEST
  }
};

export const fetchDetailsSuccess = (res) => {
    return {
      res,
      type: FETCH_USER_SUCCESS
    }
};

export const ffetchDetailsFailure = (err) => {
  return {
    err,
    type:  FETCH_USER_FAILURE
  }
};

//我是 Jest 的新手。我有以下文件。我需要为它编写单元测试。任何人都可以//帮助我应该如何开始或给我一个我可以编写的可能单元测试的抽象形式。

4

1 回答 1

0

这就是我要做的:

import {
  fetchDetailsRequest, fetchDetailsSuccess, fetchDetailsFailure, fetchDetails,
} from './myModule';
import {
  FETCH_USER_REQUEST, FETCH_USER_SUCCESS, FETCH_USER_FAILURE,
} from 'Constants/redux';
import service from 'Api/service';
import { saveError } from 'Api';

jest.mock('Api/service');
jest.mock('Api', () => ({
  ROOT_URL: 'url',
  saveError: jest.fn(),
}));

describe('my_module', () => {
  it('fetchDetailsRequest', () => {
    expect(fetchDetailsRequest()).toEqual({ type: FETCH_USER_REQUEST });
  });

  it('fetchDetailsSuccess', () => {
    const res = 'MyRes';
    expect(fetchDetailsSuccess(res)).toEqual({ res, type: FETCH_USER_SUCCESS });
  });

  it('fetchDetailsFailure', () => {
    const err = 'MyErr';
    expect(fetchDetailsFailure(err)).toEqual({ err, type: FETCH_USER_FAILURE });
  });

  describe('fetchDetails', () => {
    it('success', async () => {
      const response = 'response data';
      service.get.mockResolvedValue(response);
      const dispatch = jest.fn();
      await fetchDetails()(dispatch);
      expect(dispatch).toHaveBeenCalledTimes(2);
      expect(dispatch).toHaveBeenNthCalledWith(1, fetchDetailsRequest());
      expect(dispatch).toHaveBeenNthCalledWith(2, fetchDetailsSuccess(response));
    });

    it('failure', async () => {
      const error = 'response data';
      service.get.mockRejectedValue(error);
      const dispatch = jest.fn();
      const getState = jest.fn();
      const getStateRes = 'stateRes';
      getState.mockImplementation(() => getStateRes);
      await fetchDetails()(dispatch, getState);
      expect(dispatch).toHaveBeenCalledTimes(2);
      expect(dispatch).toHaveBeenNthCalledWith(1, fetchDetailsRequest());
      expect(dispatch).toHaveBeenNthCalledWith(2, fetchDetailsFailure(error));
      expect(saveError).toHaveBeenCalledWith(error, getStateRes);
    });
  });
});
于 2020-01-14T14:39:50.667 回答