testdouble / testdouble/testdouble.js

Stubbing a CJS module from an ESM

Open
#532 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
1.4k
Forks
140
Avg merge
22h
Merged PRs (30d)
1

Description

Description

In the testdouble repo, I created examples/node-esm/test/lib/numbers-only-test.mjs with the following code.

import assert from 'assert'
import mocha from 'mocha'
import * as td from 'testdouble'

mocha.describe('numbers-only', function () {
  mocha.it.only('goes boom', async function () {
    const isNumber = td.replace('is-number');
    const numbersOnly = await import('../../lib/numbers-only.mjs')
    td.when(isNumber('a string')).thenReturn(true) // tee-hee, this is silly

    const result = numbersOnly.default('a string')

    assert.equal(result, true)
  });
});

Based on what I read from the docs, I would expect this code to pass, but whenever ../../lib/numbers-only.mjs is loaded, the real is-number is resolved instead of the faked module.

Issue

the real module is being loaded instead of the fake.

Environment
  • node -v 20.1.0 or 22.3.0:
  • npm -v (or yarn --version) output: 10.5.2 or 10.8.1
  • npm ls testdouble (or yarn list testdouble) version: from the example
Failing Test

See above

Example Repo

See above

Runkit Notebook
  • Create a Runkit notebook
  • Invoke var td = require('testdouble') at the top
  • Verify the behavior your issue is concerned with by clicking "Run"
  • Link to the Runkit here
Code-fenced Examples
var td = require('testdouble')

// Your steps here.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running examples/node-esm/test/lib/numbers-only-test.mjs and trace td.replace('is-number') before ../../lib/numbers-only.mjs is dynamically imported. Check the ESM/CJS module-loading path involved in that example; done means the fake is-number module is used and the test assertion passes.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, node.js
Domain
devtools, testing-qa
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.