hypotes 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +293 -18
- package/dist/chain.d.ts +4 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +289 -0
- package/dist/index.d.ts +23 -10
- package/dist/index.js +422 -9
- package/dist/project-Cf9C54In.js +46 -0
- package/dist/project-filter.d.ts +14 -0
- package/dist/project.d.ts +17 -0
- package/dist/register.js +365 -10
- package/dist/reporter.d.ts +8 -0
- package/dist/reporter.js +293 -0
- package/dist/source-map.d.ts +45 -0
- package/dist/stubs.d.ts +35 -0
- package/dist/test-files.d.ts +31 -0
- package/dist/timers.d.ts +83 -0
- package/dist/wait.d.ts +47 -0
- package/package.json +24 -3
package/README.md
CHANGED
|
@@ -3,17 +3,19 @@
|
|
|
3
3
|
Vitest's API on Node's test runner. Same tests, no Vite.
|
|
4
4
|
|
|
5
5
|
Tests written with `describe`, `it`, `expect` and `vi` from hypotes run with
|
|
6
|
-
`node --test`. There is no bundler
|
|
7
|
-
runs the test files as they are, and node:test's reporters,
|
|
8
|
-
coverage apply to them.
|
|
9
|
-
[
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
6
|
+
`node --test`. There is no bundler and no config file, and node:test stays
|
|
7
|
+
the runner: Node runs the test files as they are, and node:test's reporters,
|
|
8
|
+
watch mode and coverage apply to them. The
|
|
9
|
+
[`hypotes` command](#the-hypotes-command) is a shorter way to call it. It runs
|
|
10
|
+
TypeScript by [stripping its
|
|
11
|
+
types](https://nodejs.org/api/typescript.html#type-stripping), so a test file,
|
|
12
|
+
and what it imports, has to run on Node as it's written.
|
|
13
|
+
|
|
14
|
+
Use hypotes when you want Vitest's matchers, spies, module mocks and fake
|
|
15
|
+
timers, but node:test as the runner. A test file that uses what both have
|
|
16
|
+
moves between Vitest and hypotes by changing its imports. If you need what
|
|
17
|
+
only Vitest has, such as snapshots, browser mode or Vite's transforms, use
|
|
18
|
+
Vitest: [Left out](#left-out) lists what hypotes doesn't have.
|
|
17
19
|
|
|
18
20
|
hypotes needs Node 24.13.1 or later.
|
|
19
21
|
|
|
@@ -157,6 +159,81 @@ it('greets the name in the file', () => {
|
|
|
157
159
|
Module mocks differ from Vitest's in a few ways, which
|
|
158
160
|
[Module mocks](#module-mocks) under the differences lists.
|
|
159
161
|
|
|
162
|
+
## TypeScript that Node doesn't strip
|
|
163
|
+
|
|
164
|
+
Node strips types, but rejects TypeScript that needs compiling, such as
|
|
165
|
+
enums, namespaces and parameter properties:
|
|
166
|
+
|
|
167
|
+
```text
|
|
168
|
+
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
[`@snovader/node-hooks`](https://www.npmjs.com/package/@snovader/node-hooks)
|
|
172
|
+
strips types with oxc instead, which compiles them. Its README says how else
|
|
173
|
+
it differs from Node's stripping. hypotes' module mocks work with it.
|
|
174
|
+
|
|
175
|
+
1. Install it:
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
npm install --save-dev @snovader/node-hooks
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
2. Write a module that Node can't strip, as `src/direction.ts`:
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
export enum Direction {
|
|
185
|
+
Up = 'up',
|
|
186
|
+
Down = 'down'
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
And its test, as `test/direction.test.ts`:
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
import { expect, it } from 'hypotes';
|
|
194
|
+
import { Direction } from '../src/direction.ts';
|
|
195
|
+
|
|
196
|
+
it('reads an enum', () => {
|
|
197
|
+
expect(Direction.Up).toBe('up');
|
|
198
|
+
});
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
3. Run the tests with both preloads, and with source maps:
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
node --enable-source-maps --import hypotes/register --import @snovader/node-hooks/register --test
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
```text
|
|
208
|
+
✔ reads an enum (0.699208ms)
|
|
209
|
+
✔ greets the name in the file (1.082625ms)
|
|
210
|
+
ℹ tests 2
|
|
211
|
+
ℹ suites 0
|
|
212
|
+
ℹ pass 2
|
|
213
|
+
ℹ fail 0
|
|
214
|
+
ℹ cancelled 0
|
|
215
|
+
ℹ skipped 0
|
|
216
|
+
ℹ todo 0
|
|
217
|
+
ℹ duration_ms 359.02475
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
Without module mocks, leave out `--import hypotes/register`. With them,
|
|
221
|
+
the two preloads work in either order.
|
|
222
|
+
|
|
223
|
+
oxc prints the code anew, so its lines aren't the file's. node-hooks maps
|
|
224
|
+
them back only with `--enable-source-maps`. Without it, node:test reports
|
|
225
|
+
where tests are declared, and stack traces where they fail, at the wrong
|
|
226
|
+
lines.
|
|
227
|
+
|
|
228
|
+
node-hooks' README suggests `--no-strip-types`. With it, `node --test`
|
|
229
|
+
doesn't look for `.ts` files, so name them, as in
|
|
230
|
+
`node --test "test/**/*.test.ts"`.
|
|
231
|
+
|
|
232
|
+
If you register node-hooks' resolution cache yourself, register it before
|
|
233
|
+
`hypotes/register`, so that it runs after it. Run before it, the cache keeps
|
|
234
|
+
the first resolution of each module. `vi.doMock()` then can't mock a module
|
|
235
|
+
that was imported before, and mocks of built-in modules don't apply.
|
|
236
|
+
|
|
160
237
|
## Moving a test file from Vitest
|
|
161
238
|
|
|
162
239
|
1. Import from `hypotes` what the file imports from `vitest`, and from
|
|
@@ -167,7 +244,8 @@ Module mocks differ from Vitest's in a few ways, which
|
|
|
167
244
|
name their files with the extension, as `./sum.ts`. Enums, path aliases
|
|
168
245
|
and JSX don't run, and neither does what Vite's plugins add.
|
|
169
246
|
[Type stripping](https://nodejs.org/api/typescript.html#type-stripping),
|
|
170
|
-
in Node's documentation, says what does.
|
|
247
|
+
in Node's documentation, says what does. For enums, see
|
|
248
|
+
[TypeScript that Node doesn't strip](#typescript-that-node-doesnt-strip).
|
|
171
249
|
3. Run it with `node --test`, which
|
|
172
250
|
[runs other files](#quick-start) than Vitest does. If it mocks modules,
|
|
173
251
|
set up [the preload](#mocking-modules) first.
|
|
@@ -195,9 +273,21 @@ it, apart from the differences below.
|
|
|
195
273
|
- `beforeAll`, `afterAll`, `beforeEach` and `afterEach`.
|
|
196
274
|
- `expect`, with Vitest's matchers and asymmetric matchers,
|
|
197
275
|
`expect.extend()`, `expect.addEqualityTesters()` and `expect.fail()`.
|
|
198
|
-
- `vi`, with these members:
|
|
199
|
-
`
|
|
200
|
-
|
|
276
|
+
- `vi`, with these members:
|
|
277
|
+
- For spies: `fn`, `spyOn`, `mocked`, `isMockFunction`, `clearAllMocks`,
|
|
278
|
+
`resetAllMocks` and `restoreAllMocks`.
|
|
279
|
+
- For module mocks: `mock`, `unmock`, `doMock`, `doUnmock`, `hoisted` and
|
|
280
|
+
`importActual`.
|
|
281
|
+
- For fake timers: `useFakeTimers`, `useRealTimers`, `isFakeTimers`,
|
|
282
|
+
`advanceTimersByTime`, `advanceTimersByTimeAsync`,
|
|
283
|
+
`advanceTimersToNextTimer`, `advanceTimersToNextTimerAsync`,
|
|
284
|
+
`advanceTimersToNextFrame`, `runAllTimers`, `runAllTimersAsync`,
|
|
285
|
+
`runOnlyPendingTimers`, `runOnlyPendingTimersAsync`, `runAllTicks`,
|
|
286
|
+
`getTimerCount`, `clearAllTimers`, `setSystemTime`,
|
|
287
|
+
`getMockedSystemTime`, `getRealSystemTime` and `setTimerTickMode`.
|
|
288
|
+
- For globals and environment variables: `stubGlobal`, `unstubAllGlobals`,
|
|
289
|
+
`stubEnv` and `unstubAllEnvs`.
|
|
290
|
+
- For waiting: `waitFor` and `waitUntil`.
|
|
201
291
|
|
|
202
292
|
### `hypotes/fast-check`
|
|
203
293
|
|
|
@@ -233,6 +323,16 @@ Lint rules for tests, as an oxlint JS plugin, which
|
|
|
233
323
|
The preload that module mocks need, which [Mocking modules](#mocking-modules)
|
|
234
324
|
describes.
|
|
235
325
|
|
|
326
|
+
### `hypotes/cli`
|
|
327
|
+
|
|
328
|
+
The module of [the `hypotes` command](#the-hypotes-command), which runs as
|
|
329
|
+
it's imported. Run the command instead.
|
|
330
|
+
|
|
331
|
+
### `hypotes/reporter`
|
|
332
|
+
|
|
333
|
+
A reporter for node:test that prints a row for each test file, with the name
|
|
334
|
+
of its package, which [Reporter](#reporter) describes.
|
|
335
|
+
|
|
236
336
|
## Left out
|
|
237
337
|
|
|
238
338
|
hypotes leaves out these members of Vitest's API. node:test has some of them
|
|
@@ -252,9 +352,7 @@ in another form. Of `vi`, hypotes has only the members that
|
|
|
252
352
|
| `toMatchSnapshot` and the other snapshot matchers, `expect.addSnapshotSerializer` | node:test's `t.assert.snapshot()` |
|
|
253
353
|
| `expectTypeOf`, `assertType` | The `expect-type` package, which Vitest's `expectTypeOf` comes from |
|
|
254
354
|
| `assert`, `chai`, `should` | The `chai` package, which Vitest's come from |
|
|
255
|
-
| `vi.
|
|
256
|
-
| `vi.stubGlobal` | node:test's `mock.property()`, for a global that exists |
|
|
257
|
-
| `vi.stubEnv`, `vi.resetModules`, `vi.waitFor`, `vi.waitUntil` | None |
|
|
355
|
+
| `vi.resetModules` | None |
|
|
258
356
|
| `vi.importMock`, `vi.mockObject`, automocking, `__mocks__` directories | A factory, as in `vi.mock(path, factory)` |
|
|
259
357
|
|
|
260
358
|
## Differences from Vitest
|
|
@@ -287,6 +385,39 @@ compare as `toEqual` does, such as `toContainEqual`, `toHaveProperty` and
|
|
|
287
385
|
`toHaveBeenCalledWith`. Two things that make values differ in Vitest are
|
|
288
386
|
ignored: properties set on an array besides its elements, and symbol keys.
|
|
289
387
|
|
|
388
|
+
### Fake timers, stubs and waits
|
|
389
|
+
|
|
390
|
+
The timers are Vitest's, on the version of
|
|
391
|
+
[`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers) that Vitest
|
|
392
|
+
has, and take the options of
|
|
393
|
+
[`vi.useFakeTimers()`](https://vitest.dev/api/vi#vi-usefaketimers).
|
|
394
|
+
node:test's `mock.timers` is another clock, so a test fakes the timers with
|
|
395
|
+
one of the two.
|
|
396
|
+
|
|
397
|
+
- **Options.** Vitest reads the default options from `fakeTimers` in its
|
|
398
|
+
configuration. hypotes has no configuration, so each call of
|
|
399
|
+
`vi.useFakeTimers()` passes the options that it changes.
|
|
400
|
+
- **Nothing is undone between tests.** Vitest's `unstubGlobals` and
|
|
401
|
+
`unstubEnvs` options undo the stubs after each test. Here an `afterEach`
|
|
402
|
+
calls `vi.unstubAllGlobals()` and `vi.unstubAllEnvs()`, and
|
|
403
|
+
`vi.useRealTimers()` as in Vitest. With `--test-isolation=none`, test
|
|
404
|
+
files share a process, so fake timers and stubs that a file leaves stay
|
|
405
|
+
for the files that run after it.
|
|
406
|
+
- **A clock that moves by itself keeps a test file running.** With
|
|
407
|
+
`shouldAdvanceTime`, or a tick mode besides `manual`, the fake clock moves
|
|
408
|
+
on a real timer. node:test waits for it, so a file that leaves such a
|
|
409
|
+
clock on never ends. Call `vi.useRealTimers()` in an `afterEach` or an
|
|
410
|
+
`afterAll`. Vitest ends the file's worker instead, so the file ends there
|
|
411
|
+
without it.
|
|
412
|
+
- **`process.nextTick`.** `toFake: ['nextTick']` fakes it. Vitest throws
|
|
413
|
+
instead in its default pool, `forks`.
|
|
414
|
+
- **`import.meta.env`.** `vi.stubEnv()` changes `process.env`. Vitest changes
|
|
415
|
+
`import.meta.env` too, which Vite defines and Node doesn't.
|
|
416
|
+
- **A wait ends when it settles.** In Vitest, a `vi.waitUntil()` whose
|
|
417
|
+
function throws on its first call keeps calling the function until its
|
|
418
|
+
timeout, and moves fake timers forward each time, in later tests too.
|
|
419
|
+
hypotes stops calling it.
|
|
420
|
+
|
|
290
421
|
### Module mocks
|
|
291
422
|
|
|
292
423
|
`hypotes/register` hoists the mocks of each ES module outside `node_modules`
|
|
@@ -337,6 +468,150 @@ report starts with:
|
|
|
337
468
|
Messages have colours only where Node prints them: to a terminal, or with
|
|
338
469
|
`FORCE_COLOR`, but not to a file or a pipe.
|
|
339
470
|
|
|
471
|
+
## The `hypotes` command
|
|
472
|
+
|
|
473
|
+
`hypotes` runs `node --test` with hypotes' preload and reporter, and passes
|
|
474
|
+
its other arguments on. These two commands do the same:
|
|
475
|
+
|
|
476
|
+
```bash
|
|
477
|
+
npx hypotes
|
|
478
|
+
```
|
|
479
|
+
|
|
480
|
+
```bash
|
|
481
|
+
node --import hypotes/register --test --test-reporter=hypotes/reporter
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
node:test's flags work as they do with `node --test`, as in
|
|
485
|
+
`npx hypotes --watch` or `npx hypotes "**/*.spec.ts"`. With
|
|
486
|
+
`--test-reporter`, node:test uses that reporter rather than
|
|
487
|
+
[hypotes' own](#reporter). The command exits as Node does: with 1 if a test
|
|
488
|
+
fails.
|
|
489
|
+
|
|
490
|
+
### Running one project
|
|
491
|
+
|
|
492
|
+
In a repository of several packages, `--project` runs the test files of one
|
|
493
|
+
of them, by the `name` in its `package.json`, as Vitest's `--project` does:
|
|
494
|
+
|
|
495
|
+
```bash
|
|
496
|
+
npx hypotes --project @shop/web
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
```text
|
|
500
|
+
✓ |@shop/web| test/cart.test.js (1 test) 1ms
|
|
501
|
+
|
|
502
|
+
Test Files 1 passed (1)
|
|
503
|
+
Tests 1 passed (1)
|
|
504
|
+
Duration 131ms
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
A file is in the project that [the reporter](#reporter) prints for it: the
|
|
508
|
+
nearest `package.json` above it that has a `name`.
|
|
509
|
+
|
|
510
|
+
| Command | Runs the test files of |
|
|
511
|
+
| --------------------------------------------------- | ------------------------------------- |
|
|
512
|
+
| `hypotes --project @shop/web` | `@shop/web` |
|
|
513
|
+
| `hypotes --project @shop/web --project @shop/api` | Both |
|
|
514
|
+
| `hypotes --project "@shop/*"` | Each project whose name starts so |
|
|
515
|
+
| `hypotes --project "!@shop/web"` | Each project but `@shop/web` |
|
|
516
|
+
| `hypotes --project @shop/web "**/*.spec.js"` | `@shop/web`, among those of a pattern |
|
|
517
|
+
|
|
518
|
+
node:test can't select files by their package, so with `--project` the
|
|
519
|
+
command names each selected project's directory to node:test, as a pattern.
|
|
520
|
+
node:test then finds the test files in it, as it does without `--project`.
|
|
521
|
+
|
|
522
|
+
- **Names match in any case.** `--project "@SHOP/web"` selects
|
|
523
|
+
`@shop/web`, as it does in Vitest.
|
|
524
|
+
- **Flags take their values after `=`.** Write
|
|
525
|
+
`--test-name-pattern=adds`, not `--test-name-pattern adds`: with
|
|
526
|
+
`--project`, the command takes an argument without a leading `-` for a
|
|
527
|
+
pattern of files.
|
|
528
|
+
- **No project matches.** The command fails, and lists the projects that it
|
|
529
|
+
found.
|
|
530
|
+
|
|
531
|
+
In two cases a directory's pattern would take in files of other projects,
|
|
532
|
+
so the command finds the project's files itself and names them one by one:
|
|
533
|
+
|
|
534
|
+
- with a pattern of your own, as in the last row of the table;
|
|
535
|
+
- for a project with another package inside its directory that isn't
|
|
536
|
+
selected, such as the root package of a repository.
|
|
537
|
+
|
|
538
|
+
That has costs:
|
|
539
|
+
|
|
540
|
+
- **`--watch` watches the files that it found.** A test file added later
|
|
541
|
+
runs after a restart.
|
|
542
|
+
- **A command can only be so long.** Each file is an argument to Node.
|
|
543
|
+
macOS and Linux take about a megabyte of them, and Windows 32,767
|
|
544
|
+
characters, which a few hundred files can exceed. The command then fails,
|
|
545
|
+
and says so. Select fewer files, or select the packages inside the
|
|
546
|
+
project too.
|
|
547
|
+
|
|
548
|
+
## Reporter
|
|
549
|
+
|
|
550
|
+
node:test's `spec` reporter prints each test, but not the file or the package
|
|
551
|
+
that it is in. In a repository of several packages, that makes a result hard
|
|
552
|
+
to place. `hypotes/reporter` prints a row for each test file instead, with
|
|
553
|
+
its project, as Vitest's default reporter does.
|
|
554
|
+
|
|
555
|
+
Pass it to node:test, from the root of the repository:
|
|
556
|
+
|
|
557
|
+
```bash
|
|
558
|
+
node --test --test-reporter=hypotes/reporter
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
With a test file in each of two packages, `@shop/api` and `@shop/web`, it
|
|
562
|
+
prints:
|
|
563
|
+
|
|
564
|
+
```text
|
|
565
|
+
✓ |@shop/api| test/price.test.js (2 tests) 1ms
|
|
566
|
+
✓ |@shop/web| test/cart.test.js (1 test) 1ms
|
|
567
|
+
|
|
568
|
+
Test Files 2 passed (2)
|
|
569
|
+
Tests 3 passed (3)
|
|
570
|
+
Duration 138ms
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
A file's project is the nearest `package.json` above it that has a `name`.
|
|
574
|
+
The file's path is from that package's directory. A file with no such
|
|
575
|
+
package above it has no project, and its path is from the working directory.
|
|
576
|
+
|
|
577
|
+
A file with a failure lists its failed tests. Their errors follow the files,
|
|
578
|
+
each under its file and the titles of its suites:
|
|
579
|
+
|
|
580
|
+
```text
|
|
581
|
+
❯ |@shop/api| test/price.test.js (2 tests | 1 failed) 2ms
|
|
582
|
+
× price > rounds up 1ms
|
|
583
|
+
✓ |@shop/web| test/cart.test.js (1 test) 1ms
|
|
584
|
+
|
|
585
|
+
Failed Tests 1
|
|
586
|
+
|
|
587
|
+
FAIL |@shop/api| test/price.test.js > price > rounds up
|
|
588
|
+
Error [AssertionError]: expected 3 to be 2 // Object.is equality
|
|
589
|
+
```
|
|
590
|
+
|
|
591
|
+
A file that fails as it loads, and a suite whose hook fails, aren't tests.
|
|
592
|
+
Their errors come first, under `Failed Suites`.
|
|
593
|
+
|
|
594
|
+
The error is printed as node:test's reporters print it, with its stack.
|
|
595
|
+
|
|
596
|
+
- **Colours.** Where Node prints colours, a project's name is on a coloured
|
|
597
|
+
background rather than between bars.
|
|
598
|
+
- **Other output.** What tests write to stdout and stderr, their
|
|
599
|
+
diagnostics, and the coverage report are printed as `spec` prints them.
|
|
600
|
+
The totals take the place of node:test's own.
|
|
601
|
+
- **Any node:test tests.** The reporter reads node:test's results, so it
|
|
602
|
+
reports tests declared with `node:test` too. It doesn't need
|
|
603
|
+
`hypotes/register`, and works with it.
|
|
604
|
+
- **When a row appears.** node:test reports a file's results in the order
|
|
605
|
+
that the files were found. A file's row is printed once the next file's
|
|
606
|
+
results start, so the row of a slow file holds back those after it.
|
|
607
|
+
- **Tests that a helper declares.** With `--test-isolation=none`, node:test
|
|
608
|
+
doesn't say which test file a test is from, only where it was declared.
|
|
609
|
+
Node 24.13.1 doesn't say it with any isolation. A test that a helper in
|
|
610
|
+
another module declares, as a rule tester does, is then reported under
|
|
611
|
+
that module, in a row of its own, which counts as a file in the totals.
|
|
612
|
+
- **No `--project`.** The reporter names projects, but doesn't select them.
|
|
613
|
+
[The `hypotes` command](#running-one-project) does.
|
|
614
|
+
|
|
340
615
|
## Lint rules
|
|
341
616
|
|
|
342
617
|
`hypotes/oxlint` has lint rules for tests, as an
|
package/dist/chain.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** A member of `vi` that runs, and returns `vi` */
|
|
2
|
+
export declare function chained<Vi, Args extends unknown[]>(vi: () => Vi, run: (...args: Args) => void): (...args: Args) => Vi;
|
|
3
|
+
/** A member of `vi` that runs, and returns a promise of `vi` */
|
|
4
|
+
export declare function chainedAsync<Vi, Args extends unknown[]>(vi: () => Vi, run: (...args: Args) => Promise<void>): (...args: Args) => Promise<Vi>;
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { t as Projects } from "./project-Cf9C54In.js";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import process from "node:process";
|
|
5
|
+
import { globSync } from "node:fs";
|
|
6
|
+
import { dirname, join, resolve, sep } from "node:path";
|
|
7
|
+
// source/project-filter.ts
|
|
8
|
+
/** A pattern as a regular expression of a whole name, in which `*` is any characters */
|
|
9
|
+
function toRegExp(pattern) {
|
|
10
|
+
const literals = pattern.split("*").map((literal) => RegExp.escape(literal));
|
|
11
|
+
return new RegExp(`^${literals.join(".*")}$`, "iu");
|
|
12
|
+
}
|
|
13
|
+
/** Selects projects by the patterns of `--project` */
|
|
14
|
+
var ProjectFilter = class {
|
|
15
|
+
#included;
|
|
16
|
+
#excluded;
|
|
17
|
+
/**
|
|
18
|
+
* Of patterns such as `@acme/api`, `@acme/*` and `!@acme/web`. A
|
|
19
|
+
* pattern that is empty, or only `!`, matches no project.
|
|
20
|
+
*/
|
|
21
|
+
constructor(patterns) {
|
|
22
|
+
const excluded = patterns.filter((pattern) => pattern.startsWith("!"));
|
|
23
|
+
const included = patterns.filter((pattern) => !pattern.startsWith("!"));
|
|
24
|
+
this.#included = included.map((pattern) => toRegExp(pattern));
|
|
25
|
+
this.#excluded = excluded.map((pattern) => toRegExp(pattern.slice(1)));
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Whether a project of the name is selected: no pattern with `!` matches
|
|
29
|
+
* it, and one of the others does, if there are others
|
|
30
|
+
*/
|
|
31
|
+
matches(name) {
|
|
32
|
+
if (this.#excluded.some((pattern) => pattern.test(name))) return false;
|
|
33
|
+
return this.#included.length === 0 || this.#included.some((pattern) => pattern.test(name));
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
// source/test-files.ts
|
|
37
|
+
/** The directories that node:test doesn't look for test files in */
|
|
38
|
+
const EXCLUDED = ["**/node_modules/**"];
|
|
39
|
+
/** The characters of a path that mean something else in a glob pattern */
|
|
40
|
+
const GLOB_SYNTAX = /[()*?[\]{}]/gu;
|
|
41
|
+
/**
|
|
42
|
+
* A path as a glob pattern of itself, which node:test takes each of its
|
|
43
|
+
* arguments for: `[id]` would otherwise be either letter. A character that
|
|
44
|
+
* means something in a pattern goes in a class of its own, which no
|
|
45
|
+
* platform's paths read otherwise, as they do a backslash. A leading `!`
|
|
46
|
+
* would leave the pattern's files out. A name with a comma between braces
|
|
47
|
+
* is still read as its alternatives.
|
|
48
|
+
*/
|
|
49
|
+
function escapeGlob(path) {
|
|
50
|
+
const escaped = path.replaceAll(sep, "/").replaceAll(GLOB_SYNTAX, "[$&]");
|
|
51
|
+
return escaped.startsWith("!") ? `./${escaped}` : escaped;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The pattern of the files that node:test runs when it's given none, which
|
|
55
|
+
* its documentation lists. It takes TypeScript's extensions unless Node is
|
|
56
|
+
* told not to strip types.
|
|
57
|
+
*/
|
|
58
|
+
function defaultPattern(stripsTypes) {
|
|
59
|
+
return `**/{test,test/**/*,test-*,*[._-]test}.{${stripsTypes ? "js,mjs,cjs,ts,mts,cts" : "js,mjs,cjs"}}`;
|
|
60
|
+
}
|
|
61
|
+
function isInside(directory, ancestor) {
|
|
62
|
+
return directory !== ancestor && (ancestor === "" || directory.startsWith(`${ancestor}/`));
|
|
63
|
+
}
|
|
64
|
+
/** The test files of projects under a working directory */
|
|
65
|
+
var TestFiles = class {
|
|
66
|
+
#cwd;
|
|
67
|
+
#filter;
|
|
68
|
+
#projects = new Projects();
|
|
69
|
+
/** Of the projects that the filter selects, under `cwd` */
|
|
70
|
+
constructor(cwd, filter) {
|
|
71
|
+
this.#cwd = cwd;
|
|
72
|
+
this.#filter = filter;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The names of the projects under the working directory, and of the one
|
|
76
|
+
* that it's in, in order
|
|
77
|
+
*/
|
|
78
|
+
projectNames() {
|
|
79
|
+
return [...new Set(this.#scopes().map((scope) => scope.name))].toSorted();
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The files that match the glob patterns and are in a selected project,
|
|
83
|
+
* as patterns of their paths from the working directory, in order. A
|
|
84
|
+
* file that no package with a name is above is in no project.
|
|
85
|
+
*/
|
|
86
|
+
matching(patterns) {
|
|
87
|
+
return globSync([...patterns], {
|
|
88
|
+
cwd: this.#cwd,
|
|
89
|
+
exclude: EXCLUDED
|
|
90
|
+
}).filter((file) => {
|
|
91
|
+
const project = this.#projects.of(resolve(this.#cwd, file));
|
|
92
|
+
return project !== void 0 && this.#filter.matches(project.name);
|
|
93
|
+
}).toSorted().map((file) => escapeGlob(file));
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* What names the test files of the selected projects to node:test: a
|
|
97
|
+
* pattern for a project's directory, or its files, as the header says.
|
|
98
|
+
* Nothing, if no project is selected, or none of the listed has a test
|
|
99
|
+
* file.
|
|
100
|
+
*/
|
|
101
|
+
ofProjects(pattern) {
|
|
102
|
+
const scopes = this.#scopes();
|
|
103
|
+
const selected = scopes.filter((scope) => this.#filter.matches(scope.name));
|
|
104
|
+
const whole = selected.filter((scope) => this.#isWhole(scope, scopes));
|
|
105
|
+
const patterns = whole.filter((scope) => !whole.some((other) => isInside(scope.directory, other.directory))).map(({ directory }) => directory === "" ? pattern : `${escapeGlob(directory)}/${pattern}`);
|
|
106
|
+
const files = selected.filter((scope) => !whole.includes(scope)).flatMap((scope) => this.#filesOf(scope, pattern));
|
|
107
|
+
return [...patterns, ...files];
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* The project that the working directory is in, and those in the
|
|
111
|
+
* directories under it
|
|
112
|
+
*/
|
|
113
|
+
#scopes() {
|
|
114
|
+
const scopes = [];
|
|
115
|
+
const around = this.#projects.of(join(this.#cwd, "package.json"));
|
|
116
|
+
if (around !== void 0 && around.directory !== this.#cwd) scopes.push({
|
|
117
|
+
name: around.name,
|
|
118
|
+
directory: "",
|
|
119
|
+
root: around.directory
|
|
120
|
+
});
|
|
121
|
+
for (const file of globSync("**/package.json", {
|
|
122
|
+
cwd: this.#cwd,
|
|
123
|
+
exclude: EXCLUDED
|
|
124
|
+
})) {
|
|
125
|
+
const directory = resolve(this.#cwd, dirname(file));
|
|
126
|
+
const project = this.#projects.of(join(directory, "package.json"));
|
|
127
|
+
if (project?.directory === directory) {
|
|
128
|
+
const path = dirname(file).replaceAll(sep, "/");
|
|
129
|
+
scopes.push({
|
|
130
|
+
name: project.name,
|
|
131
|
+
directory: path === "." ? "" : path,
|
|
132
|
+
root: directory
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return scopes;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Whether a pattern of the project's directory names its files, and no
|
|
140
|
+
* others: each project inside it is selected too
|
|
141
|
+
*/
|
|
142
|
+
#isWhole({ directory }, scopes) {
|
|
143
|
+
return scopes.filter((scope) => isInside(scope.directory, directory)).every((scope) => this.#filter.matches(scope.name));
|
|
144
|
+
}
|
|
145
|
+
/** The project's own files that match the pattern, not those of projects inside it */
|
|
146
|
+
#filesOf({ directory, root }, pattern) {
|
|
147
|
+
const from = resolve(this.#cwd, directory);
|
|
148
|
+
return globSync(pattern, {
|
|
149
|
+
cwd: from,
|
|
150
|
+
exclude: EXCLUDED
|
|
151
|
+
}).filter((file) => this.#projects.of(resolve(from, file))?.directory === root).map((file) => directory === "" ? file : join(directory, file)).toSorted().map((file) => escapeGlob(file));
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
// source/cli.ts
|
|
155
|
+
const USAGE = `Usage: hypotes [--project <name>]... [node's flags] [files or patterns]
|
|
156
|
+
|
|
157
|
+
Runs tests with node --test, with the preload hypotes/register and the
|
|
158
|
+
reporter hypotes/reporter. Other flags are node's, such as --watch,
|
|
159
|
+
--test-name-pattern=<pattern> and --test-reporter=<reporter>.
|
|
160
|
+
|
|
161
|
+
--project <name> Runs only the test files of the package with the name in
|
|
162
|
+
its package.json. Can be repeated. A * matches any
|
|
163
|
+
characters, and a leading ! leaves projects out.
|
|
164
|
+
-h, --help Prints this.
|
|
165
|
+
`;
|
|
166
|
+
/** Node's exit code for an invalid argument */
|
|
167
|
+
const INVALID_ARGUMENT = 9;
|
|
168
|
+
/** The signals that end a process, which the launcher passes on to Node */
|
|
169
|
+
const SIGNALS = [
|
|
170
|
+
"SIGINT",
|
|
171
|
+
"SIGTERM",
|
|
172
|
+
"SIGHUP"
|
|
173
|
+
];
|
|
174
|
+
/** An error in how the command was called, which it prints without a stack */
|
|
175
|
+
var UsageError = class extends Error {
|
|
176
|
+
#exitCode;
|
|
177
|
+
constructor(message, exitCode) {
|
|
178
|
+
super(message);
|
|
179
|
+
this.#exitCode = exitCode;
|
|
180
|
+
}
|
|
181
|
+
exitCode() {
|
|
182
|
+
return this.#exitCode;
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
function parseArguments(args) {
|
|
186
|
+
const projects = [];
|
|
187
|
+
const rest = [];
|
|
188
|
+
let help = false;
|
|
189
|
+
for (let index = 0; index < args.length; index++) {
|
|
190
|
+
const argument = args[index];
|
|
191
|
+
if (argument === "--project") {
|
|
192
|
+
index++;
|
|
193
|
+
if (index === args.length) throw new UsageError("--project needs the name of a project", INVALID_ARGUMENT);
|
|
194
|
+
projects.push(args[index]);
|
|
195
|
+
} else if (argument.startsWith("--project=")) projects.push(argument.slice(10));
|
|
196
|
+
else if (argument === "--help" || argument === "-h") help = true;
|
|
197
|
+
else rest.push(argument);
|
|
198
|
+
}
|
|
199
|
+
return {
|
|
200
|
+
projects,
|
|
201
|
+
rest,
|
|
202
|
+
help
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Node's flags among the arguments, and what names the test files of the
|
|
207
|
+
* selected projects in place of the patterns
|
|
208
|
+
*/
|
|
209
|
+
function selectFiles(projects, rest, cwd) {
|
|
210
|
+
const flags = rest.filter((argument) => argument.startsWith("-"));
|
|
211
|
+
const patterns = rest.filter((argument) => !argument.startsWith("-"));
|
|
212
|
+
const stripsTypes = !flags.some((flag) => /^--no-(?:experimental-)?strip-types$/u.test(flag));
|
|
213
|
+
const testFiles = new TestFiles(cwd, new ProjectFilter(projects));
|
|
214
|
+
const named = patterns.length === 0 ? testFiles.ofProjects(defaultPattern(stripsTypes)) : testFiles.matching(patterns);
|
|
215
|
+
if (named.length === 0) {
|
|
216
|
+
const known = testFiles.projectNames().join(", ");
|
|
217
|
+
throw new UsageError(`found no test files of --project ${projects.join(", ")}, among the projects ${known}`, 1);
|
|
218
|
+
}
|
|
219
|
+
return [...flags, ...named];
|
|
220
|
+
}
|
|
221
|
+
/** The arguments that Node runs the tests with */
|
|
222
|
+
function nodeArguments({ projects, rest }, cwd) {
|
|
223
|
+
const passed = projects.length === 0 ? rest : selectFiles(projects, rest, cwd);
|
|
224
|
+
const hasReporter = rest.some((argument) => /^--test-reporter(?:=|$)/u.test(argument));
|
|
225
|
+
return [
|
|
226
|
+
"--import",
|
|
227
|
+
import.meta.resolve("hypotes/register"),
|
|
228
|
+
"--test",
|
|
229
|
+
...hasReporter ? [] : [`--test-reporter=${import.meta.resolve("hypotes/reporter")}`],
|
|
230
|
+
...passed
|
|
231
|
+
];
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Ends this process as Node ended: with its exit code, or by its signal.
|
|
235
|
+
* Node gets the signals that this process does, or it would outlive a
|
|
236
|
+
* launcher that another process ends, as it would under `--watch`.
|
|
237
|
+
*/
|
|
238
|
+
function follow(node) {
|
|
239
|
+
const forwards = SIGNALS.map((signal) => {
|
|
240
|
+
const forward = () => {
|
|
241
|
+
node.kill(signal);
|
|
242
|
+
};
|
|
243
|
+
process.on(signal, forward);
|
|
244
|
+
return {
|
|
245
|
+
signal,
|
|
246
|
+
forward
|
|
247
|
+
};
|
|
248
|
+
});
|
|
249
|
+
node.on("exit", (code, signal) => {
|
|
250
|
+
for (const { signal: forwarded, forward } of forwards) process.off(forwarded, forward);
|
|
251
|
+
if (signal === null) process.exitCode = code ?? 1;
|
|
252
|
+
else process.kill(process.pid, signal);
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
function startFailure(error, args) {
|
|
256
|
+
const code = error.code;
|
|
257
|
+
return code === "E2BIG" || code === "ENAMETOOLONG" ? `the command that names the test files to Node is too long, with ${args.length} arguments. Select fewer files with --project or a pattern.` : `couldn't start Node: ${String(error)}`;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Starts Node. A command can only be so long, which the test files of a
|
|
261
|
+
* project that are named one by one can exceed: the system then refuses to
|
|
262
|
+
* start it.
|
|
263
|
+
*/
|
|
264
|
+
function start(args) {
|
|
265
|
+
try {
|
|
266
|
+
return spawn(process.execPath, args, { stdio: "inherit" }).on("error", (error) => {
|
|
267
|
+
process.stderr.write(`hypotes: ${startFailure(error, args)}\n`);
|
|
268
|
+
process.exitCode = 1;
|
|
269
|
+
});
|
|
270
|
+
} catch (error) {
|
|
271
|
+
throw new UsageError(startFailure(error, args), 1);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function main() {
|
|
275
|
+
const parsed = parseArguments(process.argv.slice(2));
|
|
276
|
+
if (parsed.help) {
|
|
277
|
+
process.stdout.write(USAGE);
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
follow(start(nodeArguments(parsed, process.cwd())));
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
main();
|
|
284
|
+
} catch (error) {
|
|
285
|
+
if (!(error instanceof UsageError)) throw error;
|
|
286
|
+
process.stderr.write(`hypotes: ${error.message}\n`);
|
|
287
|
+
process.exitCode = error.exitCode();
|
|
288
|
+
}
|
|
289
|
+
export {};
|