@unrift/core 0.3.0 → 0.5.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/bin/unrift.mjs +2 -1
- package/dist/esm/cli.js +19 -1
- package/dist/esm/expect.d.ts +14 -0
- package/dist/esm/expect.d.ts.map +1 -1
- package/dist/esm/index.d.ts +3 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +2 -0
- package/dist/esm/interface.d.ts +7 -3
- package/dist/esm/interface.d.ts.map +1 -1
- package/dist/esm/interface.js +9 -5
- package/dist/esm/matchers.d.ts.map +1 -1
- package/dist/esm/matchers.js +195 -1
- package/dist/esm/mock/auto.d.ts +27 -0
- package/dist/esm/mock/auto.d.ts.map +1 -0
- package/dist/esm/mock/auto.js +108 -0
- package/dist/esm/mock/fetch.d.ts +47 -0
- package/dist/esm/mock/fetch.d.ts.map +1 -0
- package/dist/esm/mock/fetch.js +149 -0
- package/dist/esm/mock/fs.d.ts +54 -0
- package/dist/esm/mock/fs.d.ts.map +1 -0
- package/dist/esm/mock/fs.js +125 -0
- package/dist/esm/mock/index.d.ts +70 -0
- package/dist/esm/mock/index.d.ts.map +1 -0
- package/dist/esm/mock/index.js +70 -0
- package/dist/esm/mock/module-loader.d.ts +66 -0
- package/dist/esm/mock/module-loader.d.ts.map +1 -0
- package/dist/esm/mock/module-loader.js +123 -0
- package/dist/esm/mock/module.d.ts +99 -0
- package/dist/esm/mock/module.d.ts.map +1 -0
- package/dist/esm/mock/module.js +198 -0
- package/dist/esm/mock/register-loader.d.ts +17 -0
- package/dist/esm/mock/register-loader.d.ts.map +1 -0
- package/dist/esm/mock/register-loader.js +45 -0
- package/dist/esm/mock/spy.d.ts +73 -0
- package/dist/esm/mock/spy.d.ts.map +1 -0
- package/dist/esm/mock/spy.js +307 -0
- package/dist/esm/mock/stub.d.ts +26 -0
- package/dist/esm/mock/stub.d.ts.map +1 -0
- package/dist/esm/mock/stub.js +82 -0
- package/dist/esm/mock/timers.d.ts +51 -0
- package/dist/esm/mock/timers.d.ts.map +1 -0
- package/dist/esm/mock/timers.js +581 -0
- package/dist/esm/run.d.ts +4 -7
- package/dist/esm/run.d.ts.map +1 -1
- package/dist/esm/run.js +6 -2
- package/dist/esm/runner.d.ts +1 -0
- package/dist/esm/runner.d.ts.map +1 -1
- package/dist/esm/runner.js +21 -10
- package/dist/esm/suite.d.ts +24 -6
- package/dist/esm/suite.d.ts.map +1 -1
- package/dist/esm/suite.js +114 -20
- package/dist/esm/test.d.ts +5 -1
- package/dist/esm/test.d.ts.map +1 -1
- package/dist/esm/test.js +20 -6
- package/dist/esm/utils/compareEngine.js +3 -3
- package/dist/esm/utils/defineConfig.d.ts +1 -0
- package/dist/esm/utils/defineConfig.d.ts.map +1 -1
- package/dist/esm/utils/discoverTestFiles.js +1 -1
- package/dist/esm/utils/helpers.d.ts +12 -0
- package/dist/esm/utils/helpers.d.ts.map +1 -1
- package/dist/esm/utils/helpers.js +20 -0
- package/dist/esm/utils/toThrow.d.ts.map +1 -1
- package/dist/esm/utils/toThrow.js +2 -1
- package/package.json +4 -3
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Module mocking - main-thread registry and public API (Tier A).
|
|
3
|
+
*
|
|
4
|
+
* Tier A scope:
|
|
5
|
+
* - `mock.doMock(spec, factory)` registers a mock for an external module
|
|
6
|
+
* specifier (bare package name or `node:*` built-in).
|
|
7
|
+
* - Subsequent `await import(spec)` calls return the factory's result.
|
|
8
|
+
* - Static imports are NOT supported in Tier A; see the docs / ISSUES.md
|
|
9
|
+
* for the planned Tier B (hoisted `mock.module`) work.
|
|
10
|
+
*
|
|
11
|
+
* Architecture:
|
|
12
|
+
* - bin/unrift.mjs registers `module-loader.js` via `module.register()` and
|
|
13
|
+
* pipes a MessagePort into the loader thread.
|
|
14
|
+
* - The main-side port is stashed on `globalThis.__unriftLoaderPort` before
|
|
15
|
+
* the test runner starts.
|
|
16
|
+
* - `doMock()` invokes the factory once, caches the result on
|
|
17
|
+
* `globalThis.__unriftMocks`, and posts a `register` message with the
|
|
18
|
+
* spec + export-key list to the loader.
|
|
19
|
+
* - The loader (see module-loader.ts) drains pending messages on every
|
|
20
|
+
* resolve() and short-circuits matched specs to a synthetic module that
|
|
21
|
+
* reads back from `globalThis.__unriftMocks`.
|
|
22
|
+
*
|
|
23
|
+
* Future tiers will reuse the same registry shape and IPC protocol -
|
|
24
|
+
* adding `register-hoisted` (Tier B) and `register-relative` (Tier C)
|
|
25
|
+
* message types without breaking the existing surface.
|
|
26
|
+
*/
|
|
27
|
+
/**
|
|
28
|
+
* Sentinel field name on globalThis. Loader-generated synthetic source
|
|
29
|
+
* reads back through this same name, so it must stay stable.
|
|
30
|
+
*/
|
|
31
|
+
export declare const MOCKS_GLOBAL_KEY = "__unriftMocks";
|
|
32
|
+
/** Sentinel field name for the IPC port set by bin/unrift.mjs. */
|
|
33
|
+
export declare const LOADER_PORT_GLOBAL_KEY = "__unriftLoaderPort";
|
|
34
|
+
/** URL prefix the loader uses for mocked modules. Public so tests can assert. */
|
|
35
|
+
export declare const MOCK_URL_PREFIX = "unrift-mock:";
|
|
36
|
+
/**
|
|
37
|
+
* Message contract between main thread and loader thread. Stable across
|
|
38
|
+
* future tiers - new message types extend this union.
|
|
39
|
+
*
|
|
40
|
+
* `registrationId` is a monotonically increasing number embedded in the
|
|
41
|
+
* synthetic mock URL. It defeats Node's URL-keyed module cache so that
|
|
42
|
+
* re-mocking the same spec in a later test yields a fresh module (rather
|
|
43
|
+
* than returning the previous test's cached mock).
|
|
44
|
+
*/
|
|
45
|
+
export type LoaderMessage = {
|
|
46
|
+
type: "register";
|
|
47
|
+
spec: string;
|
|
48
|
+
registrationId: number;
|
|
49
|
+
exportKeys: readonly string[];
|
|
50
|
+
} | {
|
|
51
|
+
type: "unregister";
|
|
52
|
+
spec: string;
|
|
53
|
+
};
|
|
54
|
+
type ModuleFactory = () => Record<string, unknown>;
|
|
55
|
+
/**
|
|
56
|
+
* Register a mock for `spec`. Subsequent `await import(spec)` calls will
|
|
57
|
+
* resolve to the factory's return value instead of the real module.
|
|
58
|
+
*
|
|
59
|
+
* Tier A constraints (planned to be lifted in Tier B and beyond):
|
|
60
|
+
* - Only **dynamic** imports (`await import(spec)`) hit the mock; static
|
|
61
|
+
* `import { x } from "spec"` is hoisted by ESM above this call and
|
|
62
|
+
* will see the real module.
|
|
63
|
+
* - Only **external** specifiers work - bare package names (`"react"`)
|
|
64
|
+
* and Node built-ins (`"node:fs"`). Relative specs (`"./bar"`) are
|
|
65
|
+
* bundled inline by esbuild and can't be intercepted at runtime.
|
|
66
|
+
* - The factory is invoked **once** at registration time. Its return
|
|
67
|
+
* value is reused for every subsequent import.
|
|
68
|
+
*
|
|
69
|
+
* Throws if the Unrift CLI loader isn't attached (i.e., tests were run
|
|
70
|
+
* with raw `node` instead of `unrift`).
|
|
71
|
+
*/
|
|
72
|
+
export declare function doMock(spec: string, factory: ModuleFactory): void;
|
|
73
|
+
/**
|
|
74
|
+
* Remove a previously registered mock. Subsequent `await import(spec)`
|
|
75
|
+
* calls fall through to the real module.
|
|
76
|
+
*/
|
|
77
|
+
export declare function unmock(spec: string): void;
|
|
78
|
+
/** Returns the current set of mocked specs. Useful for tests / debugging. */
|
|
79
|
+
export declare function listMockedSpecs(): readonly string[];
|
|
80
|
+
/**
|
|
81
|
+
* Convenience helper: imports the real module, builds a version with every
|
|
82
|
+
* function export wrapped in a spy, registers it via `mock.doMock`, and
|
|
83
|
+
* returns the mocked exports.
|
|
84
|
+
*
|
|
85
|
+
* Non-function exports are passed through unchanged. Tests can customize
|
|
86
|
+
* individual spies with `.mockReturnValue`, `.mockImplementation`, etc.
|
|
87
|
+
*
|
|
88
|
+
* Subject to the same Tier A limits as `doMock` - only affects
|
|
89
|
+
* `await import(spec)` after the call. Static imports of `spec` see the
|
|
90
|
+
* real module.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* const fs = await mock.fromModule("node:fs");
|
|
94
|
+
* fs.readFileSync.mockReturnValue("fake content");
|
|
95
|
+
* // ... test code that does `await import("node:fs")` now gets the spies
|
|
96
|
+
*/
|
|
97
|
+
export declare function fromModule<T extends Record<string, unknown>>(spec: string): Promise<T>;
|
|
98
|
+
export {};
|
|
99
|
+
//# sourceMappingURL=module.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"module.d.ts","sourceRoot":"","sources":["../../../src/mock/module.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AASH;;;GAGG;AACH,eAAO,MAAM,gBAAgB,kBAAkB,CAAC;AAEhD,kEAAkE;AAClE,eAAO,MAAM,sBAAsB,uBAAuB,CAAC;AAE3D,iFAAiF;AACjF,eAAO,MAAM,eAAe,iBAAiB,CAAC;AAE9C;;;;;;;;GAQG;AACH,MAAM,MAAM,aAAa,GACrB;IACE,IAAI,EAAE,UAAU,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;CAC/B,GACD;IAAE,IAAI,EAAE,YAAY,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAEzC,KAAK,aAAa,GAAG,MAAM,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAwFnD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,GAAG,IAAI,CAqCjE;AAED;;;GAGG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAQzC;AAED,6EAA6E;AAC7E,wBAAgB,eAAe,IAAI,SAAS,MAAM,EAAE,CAEnD;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,UAAU,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAChE,IAAI,EAAE,MAAM,GACX,OAAO,CAAC,CAAC,CAAC,CAyBZ"}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Module mocking - main-thread registry and public API (Tier A).
|
|
3
|
+
*
|
|
4
|
+
* Tier A scope:
|
|
5
|
+
* - `mock.doMock(spec, factory)` registers a mock for an external module
|
|
6
|
+
* specifier (bare package name or `node:*` built-in).
|
|
7
|
+
* - Subsequent `await import(spec)` calls return the factory's result.
|
|
8
|
+
* - Static imports are NOT supported in Tier A; see the docs / ISSUES.md
|
|
9
|
+
* for the planned Tier B (hoisted `mock.module`) work.
|
|
10
|
+
*
|
|
11
|
+
* Architecture:
|
|
12
|
+
* - bin/unrift.mjs registers `module-loader.js` via `module.register()` and
|
|
13
|
+
* pipes a MessagePort into the loader thread.
|
|
14
|
+
* - The main-side port is stashed on `globalThis.__unriftLoaderPort` before
|
|
15
|
+
* the test runner starts.
|
|
16
|
+
* - `doMock()` invokes the factory once, caches the result on
|
|
17
|
+
* `globalThis.__unriftMocks`, and posts a `register` message with the
|
|
18
|
+
* spec + export-key list to the loader.
|
|
19
|
+
* - The loader (see module-loader.ts) drains pending messages on every
|
|
20
|
+
* resolve() and short-circuits matched specs to a synthetic module that
|
|
21
|
+
* reads back from `globalThis.__unriftMocks`.
|
|
22
|
+
*
|
|
23
|
+
* Future tiers will reuse the same registry shape and IPC protocol -
|
|
24
|
+
* adding `register-hoisted` (Tier B) and `register-relative` (Tier C)
|
|
25
|
+
* message types without breaking the existing surface.
|
|
26
|
+
*/
|
|
27
|
+
import { activeRestorers, spy } from "./spy.js";
|
|
28
|
+
// The mock registry and loader port below live on globalThis, which is
|
|
29
|
+
// process-global. This is correct under unrift's sequential single-process
|
|
30
|
+
// execution; parallel per-file execution (see ISSUES.md) would need the
|
|
31
|
+
// registry keyed/isolated per worker.
|
|
32
|
+
/**
|
|
33
|
+
* Sentinel field name on globalThis. Loader-generated synthetic source
|
|
34
|
+
* reads back through this same name, so it must stay stable.
|
|
35
|
+
*/
|
|
36
|
+
export const MOCKS_GLOBAL_KEY = "__unriftMocks";
|
|
37
|
+
/** Sentinel field name for the IPC port set by bin/unrift.mjs. */
|
|
38
|
+
export const LOADER_PORT_GLOBAL_KEY = "__unriftLoaderPort";
|
|
39
|
+
/** URL prefix the loader uses for mocked modules. Public so tests can assert. */
|
|
40
|
+
export const MOCK_URL_PREFIX = "unrift-mock:";
|
|
41
|
+
function globals() {
|
|
42
|
+
return globalThis;
|
|
43
|
+
}
|
|
44
|
+
function ensureMocksMap() {
|
|
45
|
+
const slots = globals();
|
|
46
|
+
let map = slots[MOCKS_GLOBAL_KEY];
|
|
47
|
+
if (!map) {
|
|
48
|
+
map = new Map();
|
|
49
|
+
slots[MOCKS_GLOBAL_KEY] = map;
|
|
50
|
+
}
|
|
51
|
+
return map;
|
|
52
|
+
}
|
|
53
|
+
function getLoaderPort() {
|
|
54
|
+
return globals()[LOADER_PORT_GLOBAL_KEY];
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* JS identifier check. ESM `export const <key>` requires a valid identifier;
|
|
58
|
+
* keys that fail this check are skipped with a console.warn so the user
|
|
59
|
+
* isn't surprised by a silently-missing export.
|
|
60
|
+
*/
|
|
61
|
+
const IDENT_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
62
|
+
function partitionExportKeys(spec, result) {
|
|
63
|
+
const validKeys = [];
|
|
64
|
+
const skippedKeys = [];
|
|
65
|
+
for (const key of Object.keys(result)) {
|
|
66
|
+
if (key === "default" || IDENT_RE.test(key)) {
|
|
67
|
+
validKeys.push(key);
|
|
68
|
+
}
|
|
69
|
+
else {
|
|
70
|
+
skippedKeys.push(key);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (skippedKeys.length > 0) {
|
|
74
|
+
console.warn(`[unrift] mock.doMock("${spec}"): factory returned ${skippedKeys.length} key(s) that are not valid ` +
|
|
75
|
+
`JS identifiers and will not be exported: ${skippedKeys.join(", ")}`);
|
|
76
|
+
}
|
|
77
|
+
return { validKeys, skippedKeys };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Track every spec that's currently mocked so `unmock()` can find them
|
|
81
|
+
* and `restoreAll()` can clean them all up at once.
|
|
82
|
+
*/
|
|
83
|
+
const mockedSpecs = new Set();
|
|
84
|
+
/**
|
|
85
|
+
* Monotonically increasing counter - every `doMock()` call gets a unique
|
|
86
|
+
* ID embedded in its synthetic module URL, defeating Node's module cache
|
|
87
|
+
* across re-registrations.
|
|
88
|
+
*/
|
|
89
|
+
let nextRegistrationId = 0;
|
|
90
|
+
/**
|
|
91
|
+
* Restore hook registered with the spy/stub bulk-restore registry so
|
|
92
|
+
* `mock.restoreAll()` cleans up module mocks too.
|
|
93
|
+
*/
|
|
94
|
+
const restoreAllMockedSpecs = () => {
|
|
95
|
+
for (const spec of [...mockedSpecs]) {
|
|
96
|
+
unmock(spec);
|
|
97
|
+
}
|
|
98
|
+
activeRestorers.delete(restoreAllMockedSpecs);
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Register a mock for `spec`. Subsequent `await import(spec)` calls will
|
|
102
|
+
* resolve to the factory's return value instead of the real module.
|
|
103
|
+
*
|
|
104
|
+
* Tier A constraints (planned to be lifted in Tier B and beyond):
|
|
105
|
+
* - Only **dynamic** imports (`await import(spec)`) hit the mock; static
|
|
106
|
+
* `import { x } from "spec"` is hoisted by ESM above this call and
|
|
107
|
+
* will see the real module.
|
|
108
|
+
* - Only **external** specifiers work - bare package names (`"react"`)
|
|
109
|
+
* and Node built-ins (`"node:fs"`). Relative specs (`"./bar"`) are
|
|
110
|
+
* bundled inline by esbuild and can't be intercepted at runtime.
|
|
111
|
+
* - The factory is invoked **once** at registration time. Its return
|
|
112
|
+
* value is reused for every subsequent import.
|
|
113
|
+
*
|
|
114
|
+
* Throws if the Unrift CLI loader isn't attached (i.e., tests were run
|
|
115
|
+
* with raw `node` instead of `unrift`).
|
|
116
|
+
*/
|
|
117
|
+
export function doMock(spec, factory) {
|
|
118
|
+
if (typeof spec !== "string" || spec.length === 0) {
|
|
119
|
+
throw new TypeError("mock.doMock() requires a non-empty string specifier");
|
|
120
|
+
}
|
|
121
|
+
if (typeof factory !== "function") {
|
|
122
|
+
throw new TypeError("mock.doMock() requires a factory function returning an exports object");
|
|
123
|
+
}
|
|
124
|
+
const port = getLoaderPort();
|
|
125
|
+
if (!port) {
|
|
126
|
+
throw new Error("mock.doMock() requires the Unrift CLI loader to be installed. " +
|
|
127
|
+
"Run tests via the `unrift` binary (or `node bin/unrift.mjs`), not raw `node`.");
|
|
128
|
+
}
|
|
129
|
+
const result = factory();
|
|
130
|
+
if (result === null || typeof result !== "object") {
|
|
131
|
+
throw new TypeError(`mock.doMock("${spec}"): factory must return an object; got ${typeof result}`);
|
|
132
|
+
}
|
|
133
|
+
const { validKeys } = partitionExportKeys(spec, result);
|
|
134
|
+
ensureMocksMap().set(spec, result);
|
|
135
|
+
mockedSpecs.add(spec);
|
|
136
|
+
activeRestorers.add(restoreAllMockedSpecs);
|
|
137
|
+
port.postMessage({
|
|
138
|
+
type: "register",
|
|
139
|
+
spec,
|
|
140
|
+
registrationId: ++nextRegistrationId,
|
|
141
|
+
exportKeys: validKeys,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Remove a previously registered mock. Subsequent `await import(spec)`
|
|
146
|
+
* calls fall through to the real module.
|
|
147
|
+
*/
|
|
148
|
+
export function unmock(spec) {
|
|
149
|
+
const port = getLoaderPort();
|
|
150
|
+
if (port) {
|
|
151
|
+
port.postMessage({ type: "unregister", spec });
|
|
152
|
+
}
|
|
153
|
+
ensureMocksMap().delete(spec);
|
|
154
|
+
mockedSpecs.delete(spec);
|
|
155
|
+
}
|
|
156
|
+
/** Returns the current set of mocked specs. Useful for tests / debugging. */
|
|
157
|
+
export function listMockedSpecs() {
|
|
158
|
+
return [...mockedSpecs];
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Convenience helper: imports the real module, builds a version with every
|
|
162
|
+
* function export wrapped in a spy, registers it via `mock.doMock`, and
|
|
163
|
+
* returns the mocked exports.
|
|
164
|
+
*
|
|
165
|
+
* Non-function exports are passed through unchanged. Tests can customize
|
|
166
|
+
* individual spies with `.mockReturnValue`, `.mockImplementation`, etc.
|
|
167
|
+
*
|
|
168
|
+
* Subject to the same Tier A limits as `doMock` - only affects
|
|
169
|
+
* `await import(spec)` after the call. Static imports of `spec` see the
|
|
170
|
+
* real module.
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* const fs = await mock.fromModule("node:fs");
|
|
174
|
+
* fs.readFileSync.mockReturnValue("fake content");
|
|
175
|
+
* // ... test code that does `await import("node:fs")` now gets the spies
|
|
176
|
+
*/
|
|
177
|
+
export async function fromModule(spec) {
|
|
178
|
+
if (typeof spec !== "string" || spec.length === 0) {
|
|
179
|
+
throw new TypeError("mock.fromModule() requires a non-empty string specifier");
|
|
180
|
+
}
|
|
181
|
+
const real = (await import(spec));
|
|
182
|
+
const mocked = {};
|
|
183
|
+
for (const key of Object.keys(real)) {
|
|
184
|
+
const value = real[key];
|
|
185
|
+
if (typeof value === "function") {
|
|
186
|
+
// Auto-mock: create a spy with NO implementation, so unconfigured
|
|
187
|
+
// exports record calls and return undefined rather than executing the
|
|
188
|
+
// real function (which could fire real side effects). Tests opt in to
|
|
189
|
+
// behavior per export via .mockReturnValue / .mockImplementation.
|
|
190
|
+
mocked[key] = spy();
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
mocked[key] = value;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
doMock(spec, () => mocked);
|
|
197
|
+
return mocked;
|
|
198
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registers the Node module-customization hook that powers module mocking
|
|
3
|
+
* (mock.doMock / mock.fs / mock.fromModule).
|
|
4
|
+
*
|
|
5
|
+
* This is called once, early in the CLI startup (see cli.ts) - before any
|
|
6
|
+
* test file is dynamically imported. Because it lives in @unrift/core next to
|
|
7
|
+
* the loader, both the `@unrift/core` bin and the `unrift` wrapper bin get it
|
|
8
|
+
* "for free" by going through the shared CLI; neither bin needs its own
|
|
9
|
+
* bootstrap logic.
|
|
10
|
+
*
|
|
11
|
+
* The loader runs in a worker thread and receives a MessagePort over which
|
|
12
|
+
* the main thread posts register/unregister messages. The main-side port is
|
|
13
|
+
* stashed on globalThis so mock.doMock() can reach it without a circular
|
|
14
|
+
* import back into the CLI.
|
|
15
|
+
*/
|
|
16
|
+
export declare function registerModuleLoader(): void;
|
|
17
|
+
//# sourceMappingURL=register-loader.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"register-loader.d.ts","sourceRoot":"","sources":["../../../src/mock/register-loader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AASH,wBAAgB,oBAAoB,IAAI,IAAI,CAyB3C"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registers the Node module-customization hook that powers module mocking
|
|
3
|
+
* (mock.doMock / mock.fs / mock.fromModule).
|
|
4
|
+
*
|
|
5
|
+
* This is called once, early in the CLI startup (see cli.ts) - before any
|
|
6
|
+
* test file is dynamically imported. Because it lives in @unrift/core next to
|
|
7
|
+
* the loader, both the `@unrift/core` bin and the `unrift` wrapper bin get it
|
|
8
|
+
* "for free" by going through the shared CLI; neither bin needs its own
|
|
9
|
+
* bootstrap logic.
|
|
10
|
+
*
|
|
11
|
+
* The loader runs in a worker thread and receives a MessagePort over which
|
|
12
|
+
* the main thread posts register/unregister messages. The main-side port is
|
|
13
|
+
* stashed on globalThis so mock.doMock() can reach it without a circular
|
|
14
|
+
* import back into the CLI.
|
|
15
|
+
*/
|
|
16
|
+
import { register } from "node:module";
|
|
17
|
+
import { MessageChannel } from "node:worker_threads";
|
|
18
|
+
import { LOADER_PORT_GLOBAL_KEY } from "./module.js";
|
|
19
|
+
let done = false;
|
|
20
|
+
export function registerModuleLoader() {
|
|
21
|
+
if (done)
|
|
22
|
+
return;
|
|
23
|
+
done = true;
|
|
24
|
+
// `module.register()` was added in 18.19.0 / 20.6.0. On older Node, module
|
|
25
|
+
// mocking simply isn't available - doMock() throws a clear error if used.
|
|
26
|
+
if (typeof register !== "function")
|
|
27
|
+
return;
|
|
28
|
+
try {
|
|
29
|
+
const { port1, port2 } = new MessageChannel();
|
|
30
|
+
globalThis[LOADER_PORT_GLOBAL_KEY] = port1;
|
|
31
|
+
// Resolve the loader relative to this module - it's a sibling file, so no
|
|
32
|
+
// package export or cross-package specifier is involved.
|
|
33
|
+
register("./module-loader.js", import.meta.url, {
|
|
34
|
+
data: { port: port2 },
|
|
35
|
+
transferList: [port2],
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
// Best-effort: a failure here must not crash test runs that don't use
|
|
40
|
+
// module mocking.
|
|
41
|
+
if (process.env.UNRIFT_DEBUG === "1") {
|
|
42
|
+
console.warn("[unrift] module loader registration failed:", err);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Spy / Mock function primitive.
|
|
3
|
+
*
|
|
4
|
+
* Both `spy()` and `mock.fn()` produce the same object - a callable that
|
|
5
|
+
* records every invocation, supports configurable implementations, and can
|
|
6
|
+
* be restored to the original (when created via `spyOn`).
|
|
7
|
+
*/
|
|
8
|
+
export declare const SPY_BRAND: unique symbol;
|
|
9
|
+
export type AnyFn = (...args: any[]) => any;
|
|
10
|
+
export interface MockResult {
|
|
11
|
+
type: "return" | "throw";
|
|
12
|
+
value: unknown;
|
|
13
|
+
}
|
|
14
|
+
export interface MockState {
|
|
15
|
+
calls: unknown[][];
|
|
16
|
+
results: MockResult[];
|
|
17
|
+
contexts: unknown[];
|
|
18
|
+
instances: unknown[];
|
|
19
|
+
lastCall: unknown[] | undefined;
|
|
20
|
+
}
|
|
21
|
+
export interface Spy<T extends AnyFn = AnyFn> {
|
|
22
|
+
(...args: Parameters<T>): ReturnType<T>;
|
|
23
|
+
mock: MockState;
|
|
24
|
+
mockName(name: string): Spy<T>;
|
|
25
|
+
getMockName(): string;
|
|
26
|
+
mockImplementation(impl: T): Spy<T>;
|
|
27
|
+
mockImplementationOnce(impl: T): Spy<T>;
|
|
28
|
+
mockReturnValue(value: ReturnType<T>): Spy<T>;
|
|
29
|
+
mockReturnValueOnce(value: ReturnType<T>): Spy<T>;
|
|
30
|
+
mockResolvedValue(value: Awaited<ReturnType<T>>): Spy<T>;
|
|
31
|
+
mockResolvedValueOnce(value: Awaited<ReturnType<T>>): Spy<T>;
|
|
32
|
+
mockRejectedValue(error: unknown): Spy<T>;
|
|
33
|
+
mockRejectedValueOnce(error: unknown): Spy<T>;
|
|
34
|
+
mockClear(): Spy<T>;
|
|
35
|
+
mockReset(): Spy<T>;
|
|
36
|
+
mockRestore(): void;
|
|
37
|
+
readonly [SPY_BRAND]: true;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Internal registries. Used by `mock.clearAll()`, `mock.resetAll()`,
|
|
41
|
+
* and `mock.restoreAll()` to operate on every spy created so far.
|
|
42
|
+
*/
|
|
43
|
+
export declare const activeSpies: Set<Spy<AnyFn>>;
|
|
44
|
+
export declare const activeRestorers: Set<() => void>;
|
|
45
|
+
/**
|
|
46
|
+
* Returns true if the value is a spy created by `spy()` or `spyOn()`.
|
|
47
|
+
* Used by mock matchers to validate their `received` argument.
|
|
48
|
+
*/
|
|
49
|
+
export declare function isSpy(value: unknown): value is Spy;
|
|
50
|
+
/**
|
|
51
|
+
* Creates a standalone spy / mock function. Records every invocation and
|
|
52
|
+
* supports configurable behavior via `.mockReturnValue`, `.mockImplementation`, etc.
|
|
53
|
+
*/
|
|
54
|
+
export declare function spy<T extends AnyFn = AnyFn>(impl?: T): Spy<T>;
|
|
55
|
+
/**
|
|
56
|
+
* Replaces `obj[key]` with a spy that wraps the original method. Calling
|
|
57
|
+
* `.mockRestore()` (or `mock.restoreAll()`) puts the original back.
|
|
58
|
+
*
|
|
59
|
+
* The original is the default implementation - calls pass through unless
|
|
60
|
+
* the user provides an override via `.mockReturnValue` / `.mockImplementation`.
|
|
61
|
+
*
|
|
62
|
+
* The 3-arg form `spyOn(obj, "prop", "get")` / `spyOn(obj, "prop", "set")`
|
|
63
|
+
* wraps the accessor instead of a method. Setter spies record the assigned
|
|
64
|
+
* value as the first call argument; getter spies record the returned value
|
|
65
|
+
* in `mock.results`.
|
|
66
|
+
*/
|
|
67
|
+
export declare function spyOn<T extends object, K extends keyof T & (string | symbol)>(obj: T, key: K): T[K] extends AnyFn ? Spy<T[K]> : never;
|
|
68
|
+
export declare function spyOn<T extends object, K extends keyof T & (string | symbol)>(obj: T, key: K, accessor: "get"): Spy<() => T[K]>;
|
|
69
|
+
export declare function spyOn<T extends object, K extends keyof T & (string | symbol)>(obj: T, key: K, accessor: "set"): Spy<(value: T[K]) => void>;
|
|
70
|
+
export declare function clearAllMocks(): void;
|
|
71
|
+
export declare function resetAllMocks(): void;
|
|
72
|
+
export declare function restoreAllMocks(): void;
|
|
73
|
+
//# sourceMappingURL=spy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spy.d.ts","sourceRoot":"","sources":["../../../src/mock/spy.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,eAAO,MAAM,SAAS,EAAE,OAAO,MAAiC,CAAC;AAGjE,MAAM,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC;AAE5C,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;IACzB,KAAK,EAAE,OAAO,CAAC;CAChB;AAED,MAAM,WAAW,SAAS;IAExB,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC;IAEnB,OAAO,EAAE,UAAU,EAAE,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