October 31, 2019

TIL - Episode 3. Mocking node modules.

If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the mocks directory adjacent to node_modules

Mocking Node Modules, Jest Documentation

  • Once you add the mock, the template for your test would look something like this
//  src/utils/my.test.ts

afterEach(() => {
  // reset your modules after each test

test("some test that requires the non-mocked node module", () => {

  // add your test here

test("some test that mocks the fs module in order to test the expected outcome", () => {

  // add your test here
  • If you want to test out some global node object, such as process - you can do the following:
test("some test that mocks the global process object", () => {
  jest.spyOn(process, "cwd").mockImplementation(() => "well..hello there!")

  // add your test here

Jump to top of page