Replace specific module in testing

If your project is a webpack project, then https://github.com/plasticine/inject-loader is very useful. You can simply swap any dependency with a mock in just a few lines of code.

describe('MyModule', () => {
  let myModule;
  let dependencySpy;

  beforeEach(() => {
    dependencySpy= // {a mock/spy};
    myModule = require('inject-loader!./MyModule')({
      'cross-fetch': {dependencySpy},
    });
  });

  it('should call fetch', () => {
    myModule.function1();
    expect(dependencySpy.calls.length).toBe(1);
  });

});

Note: make sure you don't import the module under test at the top of your file. the require call does that part.


fetch-mock is not intended to replace the fetch() calls in the code you are testing nor do you need to change or remove any imports. Instead, it provides mock responses during your tests so that requests made with fetch() receive known, reliable responses.