Mock default export function with inbuilt node test runner

368 views Asked by At

I'm using the inbuilt node test runner, and I'm unable to mock functions that are exported in a reasonable way.

Let's start with the workaround I've found. If I export a function in this way:

wretchedExportSyntax.js

function wretchedExportSyntax() {
  return false;
}

export default {
  wretchedExportSyntax
}

Then I can write a test that mocks the function fairly easily:

index.test.js

import { test, mock } from 'node:test';
import assert from 'node:assert';

import wretchedExportSyntax from './wretchedExportSyntax.js';

function wrapper() {
  return wretchedExportSyntax.wretchedExportSyntax();
}

test('wretched export syntax', () => {
  mock.method(wretchedExportSyntax, 'wretchedExportSyntax', () => true);
  assert.equal(wretchedExportSyntax.wretchedExportSyntax(), true);
})

test('wrapper function that calls wretched export', () => {
  mock.method(wretchedExportSyntax, 'wretchedExportSyntax', () => true);
  assert.equal(wrapper(), true);
})

However, if my file has only one function, I would much prefer to export it in the following way:

defaultExport.js

export default function () {
  return false;
}

It's not a method, so I can't use mock.method(), and mock.fn() does not seem to work the way I understand it.

import defaultExport from './defaultExport.js'
test.skip('default export syntax', (t) => {
  t.mock.fn(defaultExport, () => true); // Doesn't work
  assert.equal(defaultExport(), true);
})

I've built a reduced test case here, but this issue is relevant both for functions I'm writing, as well as functions I don't have control over, like knex().

How do you mock a function that is default export using the native node test runner?

1

There are 1 answers

0
Gabriel Theron On

I referenced this question in the following issue: https://github.com/nodejs/help/issues/4298

The workaround we found since we're using CJS is to leverage this library, waiting for an official way to mock modules: https://github.com/mhweiner/cjs-mock