Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions doc/api/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -2483,16 +2483,32 @@ changes:
generates a new mock module. If `true`, subsequent calls will return the same
module mock, and the mock module is inserted into the CommonJS cache.
**Default:** false.
* `exports` {Object} Optional mocked exports. The `default` property, if
provided, is used as the mocked module's default export. All other own
enumerable properties are used as named exports.
**This option cannot be used with `defaultExport` or `namedExports`.**
* If the mock is a CommonJS or builtin module, `exports.default` is used as
the value of `module.exports`.
* If `exports.default` is not provided for a CommonJS or builtin mock,
`module.exports` defaults to an empty object.
* If named exports are provided with a non-object default export, the mock
throws an exception when used as a CommonJS or builtin module.
* `defaultExport` {any} An optional value used as the mocked module's default
export. If this value is not provided, ESM mocks do not include a default
export. If the mock is a CommonJS or builtin module, this setting is used as
the value of `module.exports`. If this value is not provided, CJS and builtin
mocks use an empty object as the value of `module.exports`.
**This option cannot be used with `options.exports`.**
This option is deprecated and will be removed in a later version.
Prefer `options.exports.default`.
* `namedExports` {Object} An optional object whose keys and values are used to
create the named exports of the mock module. If the mock is a CommonJS or
builtin module, these values are copied onto `module.exports`. Therefore, if a
mock is created with both named exports and a non-object default export, the
mock will throw an exception when used as a CJS or builtin module.
**This option cannot be used with `options.exports`.**
This option is deprecated and will be removed in a later version.
Prefer `options.exports`.
* Returns: {MockModuleContext} An object that can be used to manipulate the mock.

This function is used to mock the exports of ECMAScript modules, CommonJS modules, JSON modules, and
Expand All @@ -2509,10 +2525,10 @@ The following example demonstrates how a mock is created for a module.

```js
test('mocks a builtin module in both module systems', async (t) => {
// Create a mock of 'node:readline' with a named export named 'fn', which
// Create a mock of 'node:readline' with a named export named 'foo', which
// does not exist in the original 'node:readline' module.
const mock = t.mock.module('node:readline', {
namedExports: { fn() { return 42; } },
exports: { foo: () => 42 },
});

let esmImpl = await import('node:readline');
Expand Down
8 changes: 4 additions & 4 deletions lib/internal/test_runner/mock/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,10 @@ function defaultExportSource(useESM, hasDefaultExport) {
if (!hasDefaultExport) {
return '';
} else if (useESM) {
return 'export default $__exports.defaultExport;';
return 'export default $__exports.moduleExports.default;';
}

return 'module.exports = $__exports.defaultExport;';
return 'module.exports = $__exports.moduleExports.default;';
}

function namedExportsSource(useESM, exportNames) {
Expand All @@ -134,9 +134,9 @@ if (module.exports === null || typeof module.exports !== 'object') {
const name = exportNames[i];

if (useESM) {
source += `export let ${name} = $__exports.namedExports[${JSONStringify(name)}];\n`;
source += `export let ${name} = $__exports.moduleExports[${JSONStringify(name)}];\n`;
} else {
source += `module.exports[${JSONStringify(name)}] = $__exports.namedExports[${JSONStringify(name)}];\n`;
source += `module.exports[${JSONStringify(name)}] = $__exports.moduleExports[${JSONStringify(name)}];\n`;
}
}

Expand Down
119 changes: 92 additions & 27 deletions lib/internal/test_runner/mock/mock.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
'use strict';
const {
ArrayPrototypeFilter,
ArrayPrototypePush,
ArrayPrototypeSlice,
Error,
FunctionPrototypeBind,
FunctionPrototypeCall,
ObjectAssign,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
ObjectGetPrototypeOf,
Expand Down Expand Up @@ -33,6 +35,7 @@ const {
URLParse,
} = require('internal/url');
const {
deprecateProperty,
emitExperimentalWarning,
getStructuredStack,
kEmptyObject,
Expand Down Expand Up @@ -61,6 +64,14 @@ const kSupportedFormats = [
'module',
];
let sharedModuleState;
const deprecateNamedExports = deprecateProperty(
'namedExports',
'mock.module(): options.namedExports is deprecated. Use options.exports instead.',
);
const deprecateDefaultExport = deprecateProperty(
'defaultExport',
'mock.module(): options.defaultExport is deprecated. Use options.exports.default instead.',
);
const {
hooks: mockHooks,
mocks,
Expand Down Expand Up @@ -185,20 +196,16 @@ class MockModuleContext {
baseURL,
cache,
caller,
defaultExport,
format,
fullPath,
hasDefaultExport,
namedExports,
moduleExports,
sharedState,
specifier,
}) {
const config = {
__proto__: null,
cache,
defaultExport,
hasDefaultExport,
namedExports,
moduleExports,
caller,
};

Expand Down Expand Up @@ -230,8 +237,8 @@ class MockModuleContext {
__proto__: null,
url: baseURL,
cache,
exportNames: ObjectKeys(namedExports),
hasDefaultExport,
exportNames: ArrayPrototypeFilter(ObjectKeys(moduleExports), (k) => k !== 'default'),
hasDefaultExport: 'default' in moduleExports,
format,
localVersion,
active: true,
Expand All @@ -241,8 +248,7 @@ class MockModuleContext {
delete Module._cache[fullPath];
sharedState.mockExports.set(baseURL, {
__proto__: null,
defaultExport,
namedExports,
moduleExports,
});
}

Expand Down Expand Up @@ -627,14 +633,9 @@ class MockTracker {
debug('module mock entry, specifier = "%s", options = %o', specifier, options);

const {
cache = false,
namedExports = kEmptyObject,
defaultExport,
} = options;
const hasDefaultExport = 'defaultExport' in options;

validateBoolean(cache, 'options.cache');
validateObject(namedExports, 'options.namedExports');
cache,
moduleExports,
} = normalizeModuleMockOptions(options);

const sharedState = setupSharedModuleState();
const mockSpecifier = StringPrototypeStartsWith(specifier, 'node:') ?
Expand Down Expand Up @@ -673,11 +674,9 @@ class MockTracker {
baseURL: baseURL.href,
cache,
caller,
defaultExport,
format,
fullPath,
hasDefaultExport,
namedExports,
moduleExports,
sharedState,
specifier: mockSpecifier,
});
Expand Down Expand Up @@ -816,6 +815,73 @@ class MockTracker {
}
}

function normalizeModuleMockOptions(options) {
const { cache = false } = options;
validateBoolean(cache, 'options.cache');

const hasExports = 'exports' in options;
const hasNamedExports = 'namedExports' in options;
const hasDefaultExport = 'defaultExport' in options;

deprecateNamedExports(options);
deprecateDefaultExport(options);

const moduleExports = { __proto__: null };

if (hasExports) {
validateObject(options.exports, 'options.exports');
}

if (hasNamedExports) {
validateObject(options.namedExports, 'options.namedExports');
}

if (hasExports && (hasNamedExports || hasDefaultExport)) {
let reason = "cannot be used with 'options.namedExports'";

if (hasDefaultExport) {
reason = hasNamedExports ?
"cannot be used with 'options.namedExports' or 'options.defaultExport'" :
"cannot be used with 'options.defaultExport'";
}

throw new ERR_INVALID_ARG_VALUE('options.exports', options.exports, reason);
}

if (hasExports) {
copyOwnProperties(options.exports, moduleExports);
}

if (hasNamedExports) {
copyOwnProperties(options.namedExports, moduleExports);
}

if (hasDefaultExport) {
ObjectDefineProperty(
moduleExports,
'default',
ObjectAssign({ __proto__: null }, ObjectGetOwnPropertyDescriptor(options, 'defaultExport')),
);
}

return {
__proto__: null,
cache,
moduleExports,
};
}


function copyOwnProperties(from, to) {
const keys = ObjectKeys(from);

for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
const descriptor = ObjectGetOwnPropertyDescriptor(from, key);
ObjectDefineProperty(to, key, descriptor);
}
}

function setupSharedModuleState() {
if (sharedModuleState === undefined) {
const { mock } = require('test');
Expand Down Expand Up @@ -855,9 +921,7 @@ function cjsMockModuleLoad(request, parent, isMain) {
const {
cache,
caller,
defaultExport,
hasDefaultExport,
namedExports,
moduleExports,
} = config;

if (cache && Module._cache[resolved]) {
Expand All @@ -866,9 +930,10 @@ function cjsMockModuleLoad(request, parent, isMain) {
return Module._cache[resolved].exports;
}

const hasDefaultExport = 'default' in moduleExports;
// eslint-disable-next-line node-core/set-proto-to-null-in-object
const modExports = hasDefaultExport ? defaultExport : {};
const exportNames = ObjectKeys(namedExports);
const modExports = hasDefaultExport ? moduleExports.default : {};
const exportNames = ArrayPrototypeFilter(ObjectKeys(moduleExports), (k) => k !== 'default');

if ((typeof modExports !== 'object' || modExports === null) &&
exportNames.length > 0) {
Expand All @@ -878,7 +943,7 @@ function cjsMockModuleLoad(request, parent, isMain) {

for (let i = 0; i < exportNames.length; ++i) {
const name = exportNames[i];
const descriptor = ObjectGetOwnPropertyDescriptor(namedExports, name);
const descriptor = ObjectGetOwnPropertyDescriptor(moduleExports, name);
ObjectDefineProperty(modExports, name, descriptor);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { mock, test } from 'node:test';

const dependency = mock.fn(() => 'mock-return-value');
mock.module('../coverage-with-mock/dependency.cjs', { namedExports: { dependency } });
mock.module('../coverage-with-mock/dependency.cjs', { exports: { dependency } });

const { subject } = await import('../coverage-with-mock/subject.mjs');

Expand Down
2 changes: 1 addition & 1 deletion test/fixtures/test-runner/output/coverage-with-mock.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { describe, it, mock } from 'node:test';

describe('module test with mock', async () => {
mock.module('../coverage-with-mock/sum.js', {
namedExports: {
exports: {
sum: (a, b) => 1,
getData: () => ({}),
},
Expand Down
6 changes: 4 additions & 2 deletions test/fixtures/test-runner/output/typescript-coverage.mts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ describe('foo', { concurrency: true }, () => {
.then(({ default: _, ...rest }) => rest);

mock.module('../coverage/bar.mts', {
defaultExport: barMock,
namedExports: barNamedExports,
exports: {
...barNamedExports,
default: barMock,
},
});

({ foo } = await import('../coverage/foo.mts'));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ ok 1 - foo
# output | | | |
# typescript-coverage.mts | 100.00 | 100.00 | 100.00 |
# ----------------------------------------------------------------------------
# all files | 93.55 | 100.00 | 85.71 |
# all files | 93.94 | 100.00 | 85.71 |
# ----------------------------------------------------------------------------
# end of coverage report
Loading
Loading