ssuhat
ssuhat

Reputation: 7656

Jest call default mock from a file

I have this code on my test:

//app.test.js

jest.mock('notistack', () => ({
  useSnackbar: jest.fn(),
}));
jest
  .spyOn(notistack, 'useSnackbar')
  .mockImplementation(() => ({ enqueueSnackbar }));

How can I move this function to a single file? all of my test contains this same function and I think its redundant to keep copy paste this code. I've tried moving this to other file and make function so I can import it

// helper.js
export function snackbar() {
  jest.mock('notistack', () => ({
    useSnackbar: jest.fn(),
  }));
  jest
    .spyOn(notistack, 'useSnackbar')
    .mockImplementation(() => ({ enqueueSnackbar }));
}

// app.test.js
import {snackbar} from 'helper.js';

snackbar();
// othercode for testing;

but everytime I run it, it always return me Cannot spyOn on a primitive value; undefined given.

how can I call it properly?

Upvotes: 1

Views: 209

Answers (1)

oieduardorabelo
oieduardorabelo

Reputation: 2985

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.

Upvotes: 1

Related Questions