score:1

have a look at manual mocks guide in jest documentation.

you can create a folder called __mocks__ and replicate the modules that you want to mock there.

for example, i have a main.js file with:

let { chance } = require("chance");

let chance = chance();

function createuser() {
  return {
    id: chance.guid(),
    name: chance.name(),
    age: chance.age(),
  };
}

module.exports = { createuser };

i create a main.test.js file with:

let { createuser } = require("./main");

test("creates a new user", () => {
  let scenario = createuser();
  expect(scenario).tomatchobject({
    id: "zxcv",
    name: "foo",
    age: 20,
  });
});

now i can create a file in __mocks__/chance.js with the same signature to mock my module chance:

let chance = {};

chance.chance = function () {
  return {
    guid: () => "zxcv",
    name: () => "foo",
    age: () => 20,
  };
};

module.exports = chance;

now, every file you test that require/import chance, will use this mock by default.


Related Query

More Query from same tag