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
5 changes: 5 additions & 0 deletions packages/typescript-async-loaders/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## TypeScript and async custom loaders

Mocha 11.7.0 added support for Node's experimental [`require_module`](https://nodejs.org/docs/v22.20.0/api/modules.html#loading-ecmascript-modules-using-require) feature, which makes file loading a bit more complicated for Mocha 11. In this example, we showcase using ts-node **and** a custom asynchronous module loader to run a TypeScript test file.

This example shows more integrations than what most projects need. For a more straightforward example, see the [`typescript`](../typescript) sibling package.
7 changes: 7 additions & 0 deletions packages/typescript-async-loaders/custom-loader.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export async function load(url, context, defaultLoad) {
if (url.endsWith(".ts")) {
console.log("Loaded with custom loader");
await new Promise((resolve) => setTimeout(resolve, 1));
}
return defaultLoad(url, context, defaultLoad);
}
17 changes: 17 additions & 0 deletions packages/typescript-async-loaders/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "example-typescript-async-loaders",
"version": "1.0.0",
"type": "module",
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
},
"scripts": {
"test": "NODE_OPTIONS='--loader=ts-node/esm --loader=./custom-loader.mjs' mocha test/**/*.test.ts"
},
"devDependencies": {
"mocha": "^11.7.0",
"ts-node": "^10.9.0",
"typescript": "^5.0.0",
"@types/mocha": "^10.0.0"
}
}
12 changes: 12 additions & 0 deletions packages/typescript-async-loaders/test/async-loader.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import assert from "assert";
import { describe, it } from "mocha";

function add(a: number, b: number): number {
return a + b;
}

describe("async loaders", () => {
it("should work", () => {
assert.strictEqual(add(2, 3), 5);
});
});