首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用fetch-mock设置jest模拟

使用fetch-mock设置jest模拟
EN

Stack Overflow用户
提问于 2017-11-27 23:35:29
回答 0查看 1.8K关注 0票数 0

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

fetchFundingSource.js

代码语言:javascript
复制
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);
    }
  }
};

测试

代码语言:javascript
复制
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);
      });
  });
});
EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47514595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档