-1

I am trying to mock some native node: libraries with Node's native node:test mocking on a CJS TypeScript project. Sometimes I have success when mocking without the node: prefix, other times not.

import * as FsPromises from "node:fs/promises";
import { test } from "node:test";
import { equal } from "node:assert/strict";

test("example", async ({ mock }) => {
  mock.method(FsPromises, "glob", () => undefined)

  // ...
})

The most common error being:

 TypeError: The argument 'methodName' must be a method. Received undefined
      at MockTracker.method (node:internal/test_runner/mock/mock:515:13)
      at TestContext.<anonymous>

I would like to know how to figure out a rule of thumb on knowing if these modules are able to be mocked in a CJS project (outside of using module mocking like required in ESM). I have read that depending on the export pattern, the implementation (CJS/ESM) and more impacts the ability to mock such native libraries.

I can navigate to the TypeScript definitions of these implementations but they don't appear to give information on if these modules are mockable or not.

7
  • In general, don't mock what you don't own. Introduce a facade to mock, and/or integration test against (for fs) the actual file system. Commented Nov 2 at 12:25
  • You can't mock module "methods" on module objects, exports are readonly by design Commented Nov 2 at 12:27
  • @EstusFlask I thought that was only true of ESM? The project is set up as CJS. Can you please link the documentation as I cannot seem to find it. Commented Nov 3 at 9:39
  • @jonrsharpe I actually have wrapped the original import, I was just wondering if there is a way to test the wrapped function. For example I have tests for node:process but that was achieved by replacing process.exit directly Commented Nov 3 at 9:41
  • @myol You import it as import * as FsPromises, it's esm. It depends on the implementation of a specific module whether exports are writable, builtin modules are exotic, but as a rule of thumb you should consider them readonly. You didn't specify what your setup exactly is, including how tests are run. If you run them directly with node, ts "cjs" setup affects nothing. There's mock.module for this purpose, did you try it? Commented Nov 3 at 9:52

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.