Mock/Spy exported functions within a single module in Jest

A brief guide on how to test that a function depends on another function exported by the same module

Davide Ramaglietta
3 min readNov 12, 2018

The Problem

You have a module that exports multiple functions. One of these functions depends on another function of the same module.

export function foo () { ... }
export function bar () { foo() }

You want to assert that when executing bar() , it will also fire the execution of foo().

This would seem to be a classic situation for using Jest functionalities spyOn or mock. Therefore, you would expect to be able to write a test something like this:

import * as myModule from './myModule';test('calls myModule.foo', () => {
const fooSpy = jest.spyOn(myModule, 'foo');
myModule.bar();expect(fooSpy).toHaveBeenCalledTimes(1);
});

Surprisingly or not, this test would fail with the message Expected mock function to have been called one time, but it was called zero times.:

You could try using jest.mock() or any other Jest interface to assert that your bar method depends on your foo method.

--

--