Skip to content

Commit c2f4b08

Browse files
test_runner: support typescript module mocking
1 parent 22ea302 commit c2f4b08

File tree

7 files changed

+52
-5
lines changed

7 files changed

+52
-5
lines changed

lib/internal/modules/esm/translators.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,7 @@ translators.set('wasm', async function(url, source) {
478478
// Strategy for loading a commonjs TypeScript module
479479
translators.set('commonjs-typescript', function(url, source) {
480480
emitExperimentalWarning('Type Stripping');
481-
assertBufferSource(source, false, 'load');
481+
assertBufferSource(source, true, 'load');
482482
const code = stripTypeScriptTypes(stringify(source), url);
483483
debug(`Translating TypeScript ${url}`);
484484
return FunctionPrototypeCall(translators.get('commonjs'), this, url, code, false);
@@ -487,7 +487,7 @@ translators.set('commonjs-typescript', function(url, source) {
487487
// Strategy for loading an esm TypeScript module
488488
translators.set('module-typescript', function(url, source) {
489489
emitExperimentalWarning('Type Stripping');
490-
assertBufferSource(source, false, 'load');
490+
assertBufferSource(source, true, 'load');
491491
const code = stripTypeScriptTypes(stringify(source), url);
492492
debug(`Translating TypeScript ${url}`);
493493
return FunctionPrototypeCall(translators.get('module'), this, url, code, false);

lib/internal/test_runner/mock/loader.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ async function load(url, context, nextLoad) {
137137
async function createSourceFromMock(mock, format) {
138138
// Create mock implementation from provided exports.
139139
const { exportNames, hasDefaultExport, url } = mock;
140-
const useESM = format === 'module';
140+
const useESM = format === 'module' || format === 'module-typescript';
141141
const source = `${testImportSource(useESM)}
142142
if (!$__test.mock._mockExports.has('${url}')) {
143143
throw new Error(${JSONStringify(`mock exports not found for "${url}"`)});

lib/internal/test_runner/mock/mock.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ const kMockUnknownMessage = 3;
7070
const kWaitTimeout = 5_000;
7171
const kBadExportsMessage = 'Cannot create mock because named exports ' +
7272
'cannot be applied to the provided default export.';
73-
const kSupportedFormats = ['builtin', 'commonjs', 'module'];
73+
const kSupportedFormats = ['builtin', 'commonjs', 'module', 'module-typescript', 'commonjs-typescript'];
7474
let sharedModuleState;
7575

7676
class MockFunctionContext {
@@ -517,7 +517,10 @@ class MockTracker {
517517

518518
// Get the file that called this function. We need four stack frames:
519519
// vm context -> getStructuredStack() -> this function -> actual caller.
520-
const caller = pathToFileURL(getStructuredStack()[3]?.getFileName()).href;
520+
const filename = getStructuredStack()[3]?.getFileName();
521+
// If the caller is already a file URL, use it as is. Otherwise, convert it.
522+
const hasFileProtocol = StringPrototypeStartsWith(filename, 'file://');
523+
const caller = hasFileProtocol ? filename : pathToFileURL(filename).href;
521524
const { format, url } = sharedState.moduleLoader.resolveSync(
522525
mockSpecifier, caller, null,
523526
);

test/es-module/test-typescript.mjs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,3 +324,17 @@ test('execute a JavaScript file importing a cjs TypeScript file', async () => {
324324
match(result.stdout, /Hello, TypeScript!/);
325325
strictEqual(result.code, 0);
326326
});
327+
328+
test('execute a TypeScript test mocking module', async () => {
329+
const result = await spawnPromisified(process.execPath, [
330+
'--test',
331+
'--experimental-test-module-mocks',
332+
'--experimental-strip-types',
333+
'--no-warnings',
334+
fixtures.path('typescript/ts/test-mock-module.ts'),
335+
]);
336+
strictEqual(result.stderr, '');
337+
match(result.stdout, /Hello, TypeScript-Module!/);
338+
match(result.stdout, /Hello, TypeScript-CommonJS!/);
339+
strictEqual(result.code, 0);
340+
});
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const logger = (): void => { };
2+
3+
module.exports = {
4+
logger
5+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const logger = (): void => { };
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { before, mock, test } from 'node:test';
2+
import { strictEqual } from 'node:assert';
3+
4+
const logger = mock.fn((s) => console.log(`Hello, ${s}!`));
5+
6+
before(async () => {
7+
mock.module('./module-logger.ts', {
8+
namedExports: { logger }
9+
});
10+
mock.module('./commonjs-logger.ts', {
11+
namedExports: { logger }
12+
});
13+
});
14+
15+
test('logger', async () => {
16+
17+
const { logger: mockedModule} = await import('./module-logger.ts');
18+
mockedModule('TypeScript-Module');
19+
strictEqual(logger.mock.callCount(), 1);
20+
21+
const { logger: mockedCommonjs } = await import('./commonjs-logger.ts');
22+
mockedCommonjs('TypeScript-CommonJS');
23+
strictEqual(logger.mock.callCount(), 2);
24+
});

0 commit comments

Comments
 (0)