Jest: How to mock functions that reference each other from the same module

Kenneth Teh
2 min readMar 6, 2020

--

Finally passed!

Okay, so this is not a fully-formed article, but just a quick guide for anyone who happens to be going through the exact same thing I was.

Problem

When trying to add a simple function spec using Jest, I got stuck trying to mock a function that was referenced in the same file (was getting errors like read-only, not defined, etc.):

// Simplified for clarityexport function getOrderTotal(order) {
...
}export function getTotal(orders) { let total = orders.reduce((accumulator, order) => { return accumulator + parseFloat(getOrderTotal(order)) }, 0) ... return total}

I only wanted to test getTotal but getOrderTotal was getting in the way.

Solution

I used babel-plugin-rewire (https://github.com/speedskater/babel-plugin-rewire).

Yarn add:

yarn add babel-plugin-rewire

Add rewire plugin:

// .babelrcmodule.exports = {  presets: ['@vue/app'],  plugins: ['@babel/plugin-syntax-dynamic-import'],    env: {      test: {        presets: ['@vue/app'],        plugins: ['@babel/plugin-syntax-dynamic-import', 'rewire']      }    }}

The spec file:

import { __RewireAPI__, getTotal } from '@/assets/js/order-helper'describe('getTotal', () => {  const orders = [{}, {}] // two empty orders  // this allows mocking of a function within the same module  const getOrderTotalMock = jest.fn().mockReturnValue(100)  __RewireAPI__.__Rewire__('getOrderTotal', getOrderTotalMock)  
describe('when discount is not supplied', () => {
it('returns the total', () => { const result = getTotal(orders) ... }) )}})

We’re using Vue and ES6 (and therefore babel).

Thanks to:

https://github.com/facebook/jest/issues/936

https://medium.com/@qjli/how-to-mock-specific-module-function-in-jest-715e39a391f4

https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest

--

--

Kenneth Teh

Software Engineer primarily working with Rails and Vue.JS... sometimes DevOps and shell stuff too