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.
fs) the actual file system.node:processbut that was achieved by replacingprocess.exitdirectlyimport * 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?