Skip to content

Commit 2754e05

Browse files
committed
Add notes to docs about TS and other loaders
1 parent f45a8f3 commit 2754e05

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

‎docs/10-using-with-typescript.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,24 @@ const mockedRepository = td.object<MyRepository>();
105105
td.when(mockedRepository.findByName("Alice")).thenReturn("Alice Alicy");
106106
```
107107

108+
109+
## Replacing modules
110+
111+
`td.replace()` and `td.replaceEsm()` work with TypeScript loaders like
112+
[tsx](https://tsx.is) and [@swc-node/register](https://github.com/swc-project/swc-node).
113+
On Node.js v20.6.0 or higher, testdouble.js registers its own loader automatically,
114+
alongside whichever loader runs your TypeScript, so you don't need `--loader=testdouble`.
115+
116+
Which function you use depends on whether your TypeScript runs as ES modules or as
117+
CommonJS, not on whether your source uses `import` syntax. Most TypeScript loaders
118+
follow the same rules Node.js does:
119+
120+
* `.ts` files run as ES modules only if the nearest `package.json` has
121+
`"type": "module"`. Otherwise, they're compiled to CommonJS, and their `import`
122+
statements become `require()` calls.
123+
* `.mts` files always run as ES modules, and `.cts` files always run as CommonJS.
124+
125+
If your code runs as ES modules, use `await td.replaceEsm()` and then `await import()`
126+
your subject. If it runs as CommonJS, use `td.replace()` and then `require()` your
127+
subject. Using `td.replaceEsm()` on code that's been compiled to CommonJS fails
128+
silently: the subject still gets the real module.

‎docs/7-replacing-dependencies.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,11 @@ safely (with great power, etc.):
149149
using a test runner that does not support loaders, you can use
150150
`NODE_OPTIONS="--loader=testdouble" testrunner ...`.
151151

152+
* If you're running TypeScript through a loader like tsx, whether to use
153+
`td.replace` or `td.replaceEsm` depends on whether your files run as ES
154+
modules or get compiled to CommonJS. See [Using with
155+
TypeScript](10-using-with-typescript.md#replacing-modules).
156+
152157
That's a lot of caveats, but so long as your test and module design is simple
153158
and consistent, it's a powerful feature that can drastically simplify the setup
154159
of your isolation tests.

0 commit comments

Comments
 (0)