Search code examples
tddsinon

How to stub a JSON file with Sinon


I have a JSON file which I require in the following manner:

const things = require('./path/to/things);

I want to stub this file in a sandbox so it always returns a given fixture.


const fixture = {
  fake: "things"
}

const sandbox = sinon.createSandbox();

beforeEach(() => {
  sandbox.stub(things).returns(fixture);
});

afterEach(() => {
  sandbox.restore();
});

This lead to an error returns is not a function. I'm not sure about how to stub JSON with a sandbox. Can anyone help me?


Solution

  • You can stub only method calls. In this case the call is require(...). I think you have two options:

    1. Stub the require function.

      const sinon = require('sinon');
      const Module = require('module');
      const sandbox = sinon.createSandbox();
      sandbox.stub(Module.prototype, 'require').returns({fake:'things'});
      const things = require('./things/');
      console.log(JSON.stringify(things));
      

      Here's a repl link to the above: https://repl.it/repls/PessimisticSubtleHexagon

    2. Make your system under test depend on things and inject it. That way you decouple the logic you want to test from the import statement.