Spying on an imported function that calls another function in Jest

Only methods can be spied. There is no way to spy on funcB if it’s called directly like funcB() within same module.

In order for exported function to be spied or mocked, funcA and funcB should reside in different modules.

This allows to spy on funcB in transpiled ES module (module object is read-only in native ESM):

import { funcB } from './b';

export const funcA = () => {
    funcB()
}

Due to that module imports are representations of modules, this is transpiled to:

var _b = require('./b');

var funcA = exports.funcA = function funcA() {
    (0, _b.funcB)();
};

Where funcB method is tied to _b module object, so it’s possible to spy on it.

Leave a Comment