繁体   English   中英

用fetch-mock开玩笑

[英]jest mock setup with fetch-mock

我不知道为什么,但是测试失败,因为它说Expected mock function to have been called. 我应该如何设置addFundingSource模拟使其调用? 我不能像其他模块一样jest.mock整个模块(例如jest.mock('../../../../_helpers/alerts'); ),因为其余功能也从该模块。

fetchFundingSource.js

export const addFundingSource = () => {
  ...
}

export const fetchFundingSource = (history, onNewPaymentClose) => {
  let config = {
    ....
  };

  return async (dispatch) => {
  dispatch(fetchFundingSourceRequest());

  try {
    const response = await fetch(fundingSourceEndpoint, config);
    const jsonResponse = await response.json();
    if (!response.ok) {
      showErrorAlert(jsonResponse);
      dispatch(fetchFundingSourceError(jsonResponse));

      throw new Error(response.statusText);
    }

    dispatch(fetchFundingSourceSuccess(jsonResponse.count, jsonResponse.results));
    addFoundingSource(jsonResponse.results, history, onNewPaymentClose);
  } catch (error) {
    if (process.env.NODE_ENV === 'development') {
      console.log('Request failed', error);
    }
  }
};

测试

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as fundingSource from '../../../../dashboard/global/ducks/fetchFundingSource';
import { fundingSourceEndpoint } from '../../../../_api/companyHelpers';
import { createMemoryHistory } from 'history';

jest.mock('../../../../_api/companyHelpers');
jest.mock('../../../../_helpers/alerts');
jest.mock('../../../../_api/authHelpers');

const middlewares = [thunk];
const createMockStore = configureMockStore(middlewares);

describe('fetchFundingSource', () => {
  beforeEach(() => { fetch.resetMocks(); });
  const history = createMemoryHistory('/dashboard');
  const onNewPaymentClose = {};
  fundingSource.addFundingSource = jest.fn(); //Mock setup.

  it('dispatches the correct actions on successful fetch request', () => {
    const store = createMockStore({});
    fetch.mockResponse(JSON.stringify({ count, results }));

    const expectedActions = [
      fetchFundingSourceRequestObject,
      fetchFundingSourceSuccessObject
    ];

    return store.dispatch(fundingSource.fetchFundingSource(history, onNewPaymentClose))
      .then(() => {
        expect(fundingSource.addFundingSource).toBeCalled(); //THIS FAILS
        expect(store.getActions()).toEqual(expectedActions);
      });
  });
});

在您的示例中,我看不到实际在哪里嘲笑了命名的export addFundingSource 您可以像这样拦截和模拟导出:

import * as fundingSourceReduce from '../fetchFundingSource';
fundingSourceReduce.addFundingSource = jest.fn();

这里有更多示例。

请注意,为了确保在正确的时间设置beforeEach ,应将它们声明为beforeEach或直接声明为test的it调用。

暂无
暂无

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

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