Skip to content

Question / Bug - Unable to mock commonjs dependencies #312

@Filipoliko

Description

@Filipoliko

Hi,

thank you for this great library, thanks to this, we were able to actually use native node test runner in some of our projects!

I ran into an issue, but maybe it is expected behaviour. When I am trying to mock a dependency of a dependency, it does not really work. Maybe the issue is that both dependencies are commonjs modules?

I prepared a reproduction repository - https://github.com/Filipoliko/esmock-bug - but the use-case is quite straightforward. Ultimately, I am trying to mock fs module globally (even within dependencies like changelog-parser), but I am failing to do so. Being desperate, I tried to mock line-reader module, which is the one using the fs module in my case, but this failed also. This is a simplified example, where I was unable to mock the 3rd party dependency of a dependency.

Code

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

import esmock from 'esmock';

test('parseChangelog', async () => {
    const content = 'content';
    const parseChangelog = await esmock('changelog-parser', {}, {
        fs: { // This does not get mocked in `line-reader` module
            open: mock.fn(),
            close: mock.fn(),
            read: mock.fn(() => content),
        },
        'line-reader': { // To my surprise, even this does not get mocked in `changelog-parser` module
            readLine: mock.fn(() => content),
        }
    });

    // This leads to a real `line-reader`.readLine call, which leads to `fs.open`
    const changelog = await parseChangelog({
        filePath: 'fake',
    });

    assert.equal(changelog, content);
});

Output (Node 22.9.0)

$ node --test

✖ parseChangelog (32.4075ms)
  [Error: ENOENT: no such file or directory, open 'fake'] { errno: -2, code: 'ENOENT', syscall: 'open', path: 'fake' }

ℹ tests 1
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 358.095541

✖ failing tests:

test at repro.test.mjs:6:1
✖ parseChangelog (32.4075ms)
  [Error: ENOENT: no such file or directory, open 'fake'] { errno: -2, code: 'ENOENT', syscall: 'open', path: 'fake' }

The result is, that there is no mocked fs, nor line-reader and the test really tries to open fake file, which fails.

I am trying to use memfs as a replacement for native node fs, since we are trying to create some sort of an integration test.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions