ES6 + Mocha + Sinon: Mocking Imported Dependency


Let’s assume we have the following 2 files:-


import fetch from 'isomorphic-fetch';

export const logout = () => (
    .then(resp => resp.json())
    .catch(err => err)


import { logout } from './apis';

export const kickUserOut = activeSession => (
  activeSession ? logout() : undefined

Let’s assume we want to test the logic in service.js without using nock to mock the HTTP call in apis.js.

While proxyquireify allows us to mock out the apis.js dependency in service.js, sometimes it is a little more complicated than needed.


A simpler approach is to use sinon to stub out logout() defined in apis.js.


import { beforeEach, afterEach, describe, it } from 'mocha';
import { expect } from 'chai';
import sinon from 'sinon';
import { kickUserOut } from './service';

// import everything as an object
import * as apis from './apis';

describe('service => kickUserOut', () => {
  let logoutStub;

  // before running each test, stub out `logout()`
  beforeEach(() => {
    logoutStub = sinon.stub(apis, 'logout').returns('success');

  // after running each test, restore to the original method to
  // prevent "TypeError: Attempted to wrap logout which is already wrapped"
  // error when executing subsequent specs.
  afterEach(() => {

  it('given active session, should invoke logout API', () => {

  it('given expired session, should not invoke logout API', () => {

One thought on “ES6 + Mocha + Sinon: Mocking Imported Dependency

  1. Is this possible to do this without ES6 support.

    I suppose this must be rewritten in some way:
    import * as apis from ‘./apis’;

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 )

Google photo

You are commenting using your Google 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