Mocking dependency of module/function under test i

2019-09-16 17:45发布

问题:

Let's say I want to test the following for example:

import {fetchResourceFromBackend} from './myfetch';

const fetchSomething = (dispatch) => {

  dispatch(2);

  return fetchResourceFromBackend('/api/abc').then( result => {
    dispatch(3);
  });
};

fetchResourceFromBackend is some complicated function. How can I test this, and not be affected by fetchResourceFromBackend code (any pattern or tool recommendations, I use mocha and sinon but cannot achieve)?

Is my only option to provide fetchResourceFromBackend as an argument to fetchSomething so I can mock it?

回答1:

Using jest as @Mikhail suggested I solved like this:

// test/something-test.js

import {myFetch} from '../_mocks_/utilities';

jest.doMock('modules/utilities', () =>({
    myFetch: myFetch
}));


const {fetchSomething} = require('modules/something');

describe('#fetchSomething', ...

Here fetchSomething is function under test that has internal dependency on myFetch function from 'modules/utilities'. I mock that dependency with myFetch from '../_mocks_/utilities'.