Node.js: How to mock the imports of an ES6 module

The package mock-require is useful if you want to mock require statements in Node.js. It has a simple API that allows you to mock anything, from a single exported function to a standard library. Here’s an example:


function init() {
  // ...

module.exports = init;


import config from '../../config.js';

function load() {
  // ...

module.exports = load;


import { assert } from "chai";
import sinon from "sinon";
import mockRequire from "mock-require";

describe("My module", () => {
  let module; // module under test
  let configMock;

  beforeEach(() => {
    configMock = {
      init: sinon.stub().returns("foo"),

    // mock es6 import (tip: use the same import path)
    mockRequire("../../config.js", configMock);

    // require es6 module
    module = require("../../../app/services/content.js");

  afterEach(() => {
    // remove all registered mocks

  describe("Initialisation", () => {
    it("should have an load function", () => {


Posted in:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: