vitest-native 0.2.1 → 0.4.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/CHANGELOG.md +86 -0
- package/README.md +268 -9
- package/dist/chunk-CZWwpsFl.cjs +43 -0
- package/dist/helpers.cjs +10 -0
- package/dist/helpers.d.cts +7 -1
- package/dist/helpers.d.mts +7 -1
- package/dist/helpers.mjs +10 -1
- package/dist/{index-CJqS-y_M.d.cts → index-CJIhukN_.d.mts} +58 -4
- package/dist/{index-h4vpIkQO.d.mts → index-DEB7OFaJ.d.cts} +60 -2
- package/dist/index.cjs +296 -35
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +292 -33
- package/dist/jest-compat/interop.mjs +30 -0
- package/dist/jest-compat/jest-globals.d.mts +3 -0
- package/dist/jest-compat/jest-globals.mjs +9 -0
- package/dist/jest-compat/noop.d.mts +3 -0
- package/dist/jest-compat/noop.mjs +7 -0
- package/dist/jest-compat/setup.d.mts +3 -0
- package/dist/jest-compat/setup.mjs +41 -0
- package/dist/jest-compat.cjs +109 -0
- package/dist/jest-compat.d.cts +38 -0
- package/dist/jest-compat.d.mts +38 -0
- package/dist/jest-compat.mjs +104 -0
- package/dist/matchers.cjs +69 -0
- package/dist/matchers.d.cts +51 -0
- package/dist/matchers.d.mts +51 -0
- package/dist/matchers.mjs +66 -0
- package/dist/native/boundary.mjs +225 -0
- package/dist/native/globals.mjs +112 -0
- package/dist/native/hooks.mjs +85 -0
- package/dist/native/loader.mjs +123 -0
- package/dist/native/match.mjs +9 -0
- package/dist/native/reset.mjs +170 -0
- package/dist/native/resolve.mjs +22 -0
- package/dist/native/runner.mjs +18 -0
- package/dist/native/setup.mjs +134 -0
- package/dist/native/transform.mjs +79 -0
- package/dist/native/worker.mjs +96 -0
- package/dist/pool-B4mWN3N5.cjs +60 -0
- package/dist/pool-oPTZiSXU.mjs +58 -0
- package/dist/{preset-map-Bt4dXkZO.cjs → preset-map-C3jxnkiX.cjs} +6 -1
- package/dist/{preset-map-D224CC5w.mjs → preset-map-OJm5IWuL.mjs} +6 -1
- package/dist/{presets-9Y4ssfiH.cjs → presets-2I68Ipyl.cjs} +768 -122
- package/dist/{presets-CWH0gtM0.mjs → presets-DOGXQzYT.mjs} +732 -87
- package/dist/presets.cjs +5 -1
- package/dist/presets.d.cts +2 -2
- package/dist/presets.d.mts +2 -2
- package/dist/presets.mjs +2 -2
- package/dist/setup.cjs +903 -121
- package/dist/setup.mjs +899 -118
- package/docs/migrating-from-jest.md +123 -0
- package/docs/migrating-from-vitest-react-native.md +109 -0
- package/package.json +67 -8
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Globals React Native core expects at runtime, ported from react-native/jest/setup.js.
|
|
2
|
+
export function installGlobals() {
|
|
3
|
+
const g = globalThis;
|
|
4
|
+
Object.defineProperties(g, {
|
|
5
|
+
__DEV__: { configurable: true, writable: true, value: true },
|
|
6
|
+
requestAnimationFrame: {
|
|
7
|
+
configurable: true,
|
|
8
|
+
writable: true,
|
|
9
|
+
value: (cb) => setTimeout(() => cb(Date.now()), 0),
|
|
10
|
+
},
|
|
11
|
+
cancelAnimationFrame: {
|
|
12
|
+
configurable: true,
|
|
13
|
+
writable: true,
|
|
14
|
+
value: (id) => clearTimeout(id),
|
|
15
|
+
},
|
|
16
|
+
nativeFabricUIManager: { configurable: true, writable: true, value: {} },
|
|
17
|
+
...(typeof g.window === "undefined"
|
|
18
|
+
? { window: { configurable: true, writable: true, value: g } }
|
|
19
|
+
: {}),
|
|
20
|
+
});
|
|
21
|
+
g.IS_REACT_ACT_ENVIRONMENT = true;
|
|
22
|
+
g.IS_REACT_NATIVE_TEST_ENVIRONMENT = true;
|
|
23
|
+
g.__fbBatchedBridgeConfig = { remoteModuleConfig: [], localModulesConfig: [] };
|
|
24
|
+
|
|
25
|
+
installExpoGlobal(g);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// expo-modules-core's JS reads its native runtime off `globalThis.expo`
|
|
29
|
+
// (`globalThis.expo.EventEmitter`, `.NativeModule`, `.SharedObject`, `.SharedRef`,
|
|
30
|
+
// `.modules`, …). The native build installs this; Node has no native runtime, so
|
|
31
|
+
// expo-modules-core throws ("Cannot read properties of undefined (reading
|
|
32
|
+
// 'EventEmitter')") and every Expo-modules-based library fails to import. Provide a
|
|
33
|
+
// JS stub so the real expo-modules-core runs — same approach jest-expo takes.
|
|
34
|
+
function installExpoGlobal(g) {
|
|
35
|
+
if (g.expo && g.expo.EventEmitter) return;
|
|
36
|
+
|
|
37
|
+
class EventEmitter {
|
|
38
|
+
constructor() {
|
|
39
|
+
this._listeners = new Map();
|
|
40
|
+
}
|
|
41
|
+
addListener(eventName, listener) {
|
|
42
|
+
let set = this._listeners.get(eventName);
|
|
43
|
+
if (!set) this._listeners.set(eventName, (set = new Set()));
|
|
44
|
+
set.add(listener);
|
|
45
|
+
return { remove: () => this.removeListener(eventName, listener) };
|
|
46
|
+
}
|
|
47
|
+
removeListener(eventName, listener) {
|
|
48
|
+
this._listeners.get(eventName)?.delete(listener);
|
|
49
|
+
}
|
|
50
|
+
removeAllListeners(eventName) {
|
|
51
|
+
if (eventName == null) this._listeners.clear();
|
|
52
|
+
else this._listeners.delete(eventName);
|
|
53
|
+
}
|
|
54
|
+
emit(eventName, ...args) {
|
|
55
|
+
this._listeners.get(eventName)?.forEach((l) => l(...args));
|
|
56
|
+
}
|
|
57
|
+
listenerCount(eventName) {
|
|
58
|
+
return this._listeners.get(eventName)?.size ?? 0;
|
|
59
|
+
}
|
|
60
|
+
startObserving() {}
|
|
61
|
+
stopObserving() {}
|
|
62
|
+
}
|
|
63
|
+
// NativeModule / SharedObject / SharedRef extend EventEmitter in expo's runtime.
|
|
64
|
+
class NativeModule extends EventEmitter {}
|
|
65
|
+
class SharedObject extends EventEmitter {}
|
|
66
|
+
class SharedRef extends SharedObject {}
|
|
67
|
+
|
|
68
|
+
// `globalThis.expo.modules` is the native-module registry expo libs read via
|
|
69
|
+
// requireNativeModule(). Import-time side effects (e.g. expo-modules-core's
|
|
70
|
+
// setUpJsLogger) call methods like `.addListener` on these, so return a
|
|
71
|
+
// permissive NativeModule stub (EventEmitter methods + no-op for unknown native
|
|
72
|
+
// methods) for any accessed module rather than crashing on `undefined`.
|
|
73
|
+
const __moduleCache = new Map();
|
|
74
|
+
const makeModuleStub = () =>
|
|
75
|
+
new Proxy(new NativeModule(), {
|
|
76
|
+
get(target, prop) {
|
|
77
|
+
if (prop in target) return target[prop];
|
|
78
|
+
if (typeof prop === "symbol") return undefined;
|
|
79
|
+
return () => undefined;
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
const modules = new Proxy(
|
|
83
|
+
{},
|
|
84
|
+
{
|
|
85
|
+
get(_t, prop) {
|
|
86
|
+
if (typeof prop === "symbol") return undefined;
|
|
87
|
+
if (!__moduleCache.has(prop)) __moduleCache.set(prop, makeModuleStub());
|
|
88
|
+
return __moduleCache.get(prop);
|
|
89
|
+
},
|
|
90
|
+
has: () => true,
|
|
91
|
+
},
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
let __uuid = 0;
|
|
95
|
+
g.expo = {
|
|
96
|
+
EventEmitter,
|
|
97
|
+
NativeModule,
|
|
98
|
+
SharedObject,
|
|
99
|
+
SharedRef,
|
|
100
|
+
modules,
|
|
101
|
+
uuidv4: () => {
|
|
102
|
+
__uuid += 1;
|
|
103
|
+
return `00000000-0000-4000-8000-${String(__uuid).padStart(12, "0")}`;
|
|
104
|
+
},
|
|
105
|
+
uuid: {
|
|
106
|
+
v4: () => g.expo.uuidv4(),
|
|
107
|
+
v5: () => g.expo.uuidv4(),
|
|
108
|
+
},
|
|
109
|
+
getViewConfig: () => null,
|
|
110
|
+
reloadAppAsync: () => Promise.resolve(),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Patches Node's CJS loader so RN's internal require() chains are Flow-stripped and
|
|
2
|
+
// native-boundary modules are mocked. The companion loader.mjs handles the import() path.
|
|
3
|
+
import Module from "node:module";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import { transformRN, isFlow } from "./transform.mjs";
|
|
7
|
+
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
|
+
import { resolvePlatformFile } from "./resolve.mjs";
|
|
9
|
+
import { buildPkgMatcher } from "./match.mjs";
|
|
10
|
+
|
|
11
|
+
const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
|
|
12
|
+
|
|
13
|
+
// Guarded via globalThis, not module scope: under the hot runtime this module
|
|
14
|
+
// can be evaluated twice in one worker (once by the worker entry through Node's
|
|
15
|
+
// loader, once through Vitest's module runner when the setup file is inlined),
|
|
16
|
+
// and the hooks must still install exactly once per worker.
|
|
17
|
+
export function installRequireHooks(projectRoot, transformPkgs = []) {
|
|
18
|
+
if (globalThis.__vitest_native_require_hooks_installed) return;
|
|
19
|
+
globalThis.__vitest_native_require_hooks_installed = true;
|
|
20
|
+
|
|
21
|
+
// Configured third-party packages to also transform (Flow/TS/JSX stripped).
|
|
22
|
+
const isExtra = buildPkgMatcher(transformPkgs);
|
|
23
|
+
|
|
24
|
+
// Preset redirect (CJS): when an externalized third-party module require()s a
|
|
25
|
+
// preset package by its bare name (e.g. @gorhom/bottom-sheet → require(
|
|
26
|
+
// 'react-native-gesture-handler'), or moti → require('react-native-reanimated')),
|
|
27
|
+
// serve the runtime preset mock instead of loading the real native lib. The Vite
|
|
28
|
+
// plugin already redirects the app/test graph's *direct* imports; this closes the
|
|
29
|
+
// gap for nested requires that reach Node's CJS loader and would otherwise hit
|
|
30
|
+
// the real package's native runtime. The lookup is dynamic (no preset-name list
|
|
31
|
+
// captured at install time) so the hooks can install at hot-worker boot, before
|
|
32
|
+
// the setup file has built the preset mocks.
|
|
33
|
+
const origLoad = Module._load;
|
|
34
|
+
Module._load = function (request, parent, ...rest) {
|
|
35
|
+
const mocks = globalThis.__vitest_native_preset_mocks;
|
|
36
|
+
if (mocks && Object.prototype.hasOwnProperty.call(mocks, request)) return mocks[request];
|
|
37
|
+
return origLoad.call(this, request, parent, ...rest);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const origResolve = Module._resolveFilename;
|
|
41
|
+
Module._resolveFilename = function (request, parent, ...rest) {
|
|
42
|
+
if (
|
|
43
|
+
parent &&
|
|
44
|
+
parent.filename &&
|
|
45
|
+
RN_PATH.test(parent.filename) &&
|
|
46
|
+
request.startsWith(".") &&
|
|
47
|
+
!path.extname(request)
|
|
48
|
+
) {
|
|
49
|
+
const hit = resolvePlatformFile(path.resolve(path.dirname(parent.filename), request));
|
|
50
|
+
if (hit) return hit;
|
|
51
|
+
}
|
|
52
|
+
return origResolve.call(this, request, parent, ...rest);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const origJs = Module._extensions[".js"];
|
|
56
|
+
Module._extensions[".js"] = function (mod, filename) {
|
|
57
|
+
const norm = filename.replace(/\\/g, "/");
|
|
58
|
+
const boundary = boundarySourceFor(norm);
|
|
59
|
+
if (boundary != null) return mod._compile(boundary, filename);
|
|
60
|
+
if (RN_PATH.test(norm)) {
|
|
61
|
+
const src = fs.readFileSync(filename, "utf8");
|
|
62
|
+
if (isFlow(src)) return mod._compile(transformRN(filename, src, projectRoot), filename);
|
|
63
|
+
} else if (isExtra(norm)) {
|
|
64
|
+
// Configured third-party packages: transform unconditionally — TS `import
|
|
65
|
+
// type`/JSX aren't caught by isFlow, and babel passes plain JS through.
|
|
66
|
+
const src = fs.readFileSync(filename, "utf8");
|
|
67
|
+
return mod._compile(transformRN(filename, src, projectRoot), filename);
|
|
68
|
+
}
|
|
69
|
+
return origJs(mod, filename);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// Node's CJS loader has no `.ts`/`.tsx` handler, so a synchronous
|
|
73
|
+
// `jest.requireActual('./app/Component')` (common in migrated Jest suites, e.g.
|
|
74
|
+
// to spread a real module then override one export) fails to load app TypeScript.
|
|
75
|
+
// App/test code normally runs through Vite; these handlers only fire for Node
|
|
76
|
+
// requires (i.e. requireActual + its transitive requires). Transform via the
|
|
77
|
+
// project's RN Babel preset (strips TS + JSX → CJS).
|
|
78
|
+
for (const ext of [".ts", ".tsx"]) {
|
|
79
|
+
if (Module._extensions[ext]) continue;
|
|
80
|
+
Module._extensions[ext] = function (mod, filename) {
|
|
81
|
+
const src = fs.readFileSync(filename, "utf8");
|
|
82
|
+
return mod._compile(transformRN(filename, src, projectRoot), filename);
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Node ESM loader hook (registered via module.register). Intercepts import() of RN —
|
|
2
|
+
// which Module._extensions cannot — Flow-stripping and serving boundary mock source.
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import { transformRN, isFlow } from "./transform.mjs";
|
|
7
|
+
import { boundarySourceFor } from "./boundary.mjs";
|
|
8
|
+
import { resolvePlatformFile } from "./resolve.mjs";
|
|
9
|
+
import { buildPkgMatcher } from "./match.mjs";
|
|
10
|
+
|
|
11
|
+
const RN_PATH = /[\\/](react-native|@react-native)[\\/]/;
|
|
12
|
+
const TRANSFORMABLE = /\.(jsx?|tsx?|mjs|cjs)$/;
|
|
13
|
+
// Extensions/index candidates for bundler-style extensionless resolution.
|
|
14
|
+
const RESOLVE_EXTS = [".js", ".cjs", ".mjs", ".json", ".jsx", ".ts", ".tsx"];
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Bundler-style resolution for an extensionless relative import: try `base+ext`
|
|
18
|
+
* then `base/index+ext`. Metro/webpack accept these; Node's strict ESM resolver
|
|
19
|
+
* doesn't, which breaks externalized libs that ship ESM with extensionless imports
|
|
20
|
+
* (e.g. @expo/vector-icons' `import './createIconSet'`, react-native-webview's
|
|
21
|
+
* `./WebView`). Returns the on-disk path, or null.
|
|
22
|
+
*/
|
|
23
|
+
function resolveExtensionless(base) {
|
|
24
|
+
for (const ext of RESOLVE_EXTS) {
|
|
25
|
+
const f = base + ext;
|
|
26
|
+
if (fs.existsSync(f)) return f;
|
|
27
|
+
}
|
|
28
|
+
for (const ext of RESOLVE_EXTS) {
|
|
29
|
+
const f = path.join(base, "index" + ext);
|
|
30
|
+
if (fs.existsSync(f)) return f;
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
// Synthetic URL scheme for preset mocks served to the ESM graph (see below).
|
|
35
|
+
const PRESET_SCHEME = "vitest-native-preset:";
|
|
36
|
+
let PROJECT_ROOT = process.cwd();
|
|
37
|
+
let isExtra = () => false;
|
|
38
|
+
// Preset package name → its mock's named-export list (from the preset definition).
|
|
39
|
+
let presetExports = {};
|
|
40
|
+
|
|
41
|
+
export async function initialize(data) {
|
|
42
|
+
if (data && data.projectRoot) PROJECT_ROOT = data.projectRoot;
|
|
43
|
+
if (data && data.transformPkgs) isExtra = buildPkgMatcher(data.transformPkgs);
|
|
44
|
+
if (data && data.presetExports) presetExports = data.presetExports;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function resolve(specifier, context, nextResolve) {
|
|
48
|
+
// Preset redirect (ESM): a bare import of a preset package — whether from the
|
|
49
|
+
// test graph or, crucially, nested inside an externalized third-party lib — is
|
|
50
|
+
// redirected to a synthetic module that re-exports the runtime preset mock. This
|
|
51
|
+
// mirrors the Vite plugin's virtual:preset modules for the Node ESM path.
|
|
52
|
+
if (Object.prototype.hasOwnProperty.call(presetExports, specifier)) {
|
|
53
|
+
return { url: PRESET_SCHEME + specifier, shortCircuit: true };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const parent =
|
|
57
|
+
context.parentURL && context.parentURL.startsWith("file:")
|
|
58
|
+
? fileURLToPath(context.parentURL)
|
|
59
|
+
: null;
|
|
60
|
+
if (parent && RN_PATH.test(parent) && specifier.startsWith(".") && !path.extname(specifier)) {
|
|
61
|
+
const hit = resolvePlatformFile(path.resolve(path.dirname(parent), specifier));
|
|
62
|
+
if (hit) return { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
return await nextResolve(specifier, context);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
// Fallback: an extensionless relative import that Node's ESM resolver rejected
|
|
69
|
+
// but a bundler (Metro) would accept. Common in externalized RN libs shipping
|
|
70
|
+
// ESM with extensionless imports. Resolve it on disk ourselves.
|
|
71
|
+
if (parent && specifier.startsWith(".") && !path.extname(specifier)) {
|
|
72
|
+
const hit = resolveExtensionless(path.resolve(path.dirname(parent), specifier));
|
|
73
|
+
if (hit) return { url: pathToFileURL(hit).href, shortCircuit: true };
|
|
74
|
+
}
|
|
75
|
+
throw err;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function load(url, context, nextLoad) {
|
|
80
|
+
// Serve the synthetic preset module. The generated source reads the mock built
|
|
81
|
+
// by the native setup file from globalThis (this source executes in the main
|
|
82
|
+
// realm, so globalThis is the populated one), mirroring the Vite virtual:preset.
|
|
83
|
+
if (url.startsWith(PRESET_SCHEME)) {
|
|
84
|
+
const pkg = url.slice(PRESET_SCHEME.length);
|
|
85
|
+
const names = presetExports[pkg] || [];
|
|
86
|
+
const source = [
|
|
87
|
+
`const _m = (globalThis.__vitest_native_preset_mocks || {})[${JSON.stringify(pkg)}] || {};`,
|
|
88
|
+
...names.map((n) => `export const ${n} = _m[${JSON.stringify(n)}];`),
|
|
89
|
+
// Honor a factory-provided default (e.g. svg's default Svg component);
|
|
90
|
+
// only fall back to the namespace object when the mock has none.
|
|
91
|
+
`export default ("default" in _m ? _m["default"] : _m);`,
|
|
92
|
+
].join("\n");
|
|
93
|
+
return { format: "module", source, shortCircuit: true };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (!url.startsWith("file:")) return nextLoad(url, context);
|
|
97
|
+
const file = fileURLToPath(url);
|
|
98
|
+
const norm = file.replace(/\\/g, "/");
|
|
99
|
+
const isRN = RN_PATH.test(norm);
|
|
100
|
+
if (!isRN && !isExtra(norm)) return nextLoad(url, context);
|
|
101
|
+
|
|
102
|
+
if (isRN) {
|
|
103
|
+
const boundary = boundarySourceFor(norm);
|
|
104
|
+
if (boundary != null) return { format: "commonjs", source: boundary, shortCircuit: true };
|
|
105
|
+
if (norm.endsWith(".js")) {
|
|
106
|
+
const src = fs.readFileSync(file, "utf8");
|
|
107
|
+
if (isFlow(src))
|
|
108
|
+
return {
|
|
109
|
+
format: "commonjs",
|
|
110
|
+
source: transformRN(file, src, PROJECT_ROOT),
|
|
111
|
+
shortCircuit: true,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
return nextLoad(url, context);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Configured third-party package: transform any JS/TS/JSX source to CJS.
|
|
118
|
+
if (TRANSFORMABLE.test(norm)) {
|
|
119
|
+
const src = fs.readFileSync(file, "utf8");
|
|
120
|
+
return { format: "commonjs", source: transformRN(file, src, PROJECT_ROOT), shortCircuit: true };
|
|
121
|
+
}
|
|
122
|
+
return nextLoad(url, context);
|
|
123
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Builds a predicate that matches files located under any of the given
|
|
2
|
+
// node_modules package names (used by both the require hook and the ESM loader
|
|
3
|
+
// to extend transformation to configured third-party RN libraries).
|
|
4
|
+
export function buildPkgMatcher(pkgs) {
|
|
5
|
+
const res = (pkgs || []).map(
|
|
6
|
+
(p) => new RegExp("[\\\\/]" + p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "[\\\\/]"),
|
|
7
|
+
);
|
|
8
|
+
return (normPath) => res.some((re) => re.test(normPath));
|
|
9
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// Surgical per-file reset for the hot runtime (see worker.mjs and runner.mjs).
|
|
2
|
+
//
|
|
3
|
+
// Vitest's own per-file reset (run with config.isolate flipped on by worker.mjs)
|
|
4
|
+
// already re-evaluates everything in the module-runner graph — test files, app
|
|
5
|
+
// source, setup files. What it can NOT touch is state living in the worker's
|
|
6
|
+
// resident Node require cache: React Native itself (externalized by design),
|
|
7
|
+
// other externalized CJS deps, and our boundary mocks. This module covers that
|
|
8
|
+
// gap with an import-phase/test-phase attribution model:
|
|
9
|
+
//
|
|
10
|
+
// THE ATTRIBUTION PROBLEM: a resident (externalized) library that lazily
|
|
11
|
+
// initializes during a file's IMPORT phase creates globals/listeners exactly
|
|
12
|
+
// once — tear those down and the library breaks for every later file, because
|
|
13
|
+
// its module init never re-runs (found the hard way: deleting Storybook's
|
|
14
|
+
// __STORYBOOK_ADDONS_PREVIEW registry made every later story render empty).
|
|
15
|
+
// State created during the TEST phase, by contrast, is pollution to remove.
|
|
16
|
+
//
|
|
17
|
+
// The split is observable: runner.mjs calls bless() from onBeforeRunFiles —
|
|
18
|
+
// after the test module (and its resident deps) finished importing, before
|
|
19
|
+
// any test runs. Everything present at bless() joins the baseline; everything
|
|
20
|
+
// that appears after it is test-phase pollution, reset by hotReset() at the
|
|
21
|
+
// NEXT file's setup. If bless() never fires (consumer overrode `runner`), the
|
|
22
|
+
// attribution-dependent teardowns stay disarmed — fail-open to stock
|
|
23
|
+
// isolate:false semantics rather than guessing.
|
|
24
|
+
//
|
|
25
|
+
// Covered surfaces:
|
|
26
|
+
// 1. RN event listeners — every NativeEventEmitter (AppState, Appearance,
|
|
27
|
+
// Keyboard, …) delegates to the RCTDeviceEventEmitter singleton, so one
|
|
28
|
+
// wrapped addListener tracks the whole RN JS event surface. Test-phase
|
|
29
|
+
// subscriptions are removed via their own public subscription.remove();
|
|
30
|
+
// import-phase subscriptions are blessed.
|
|
31
|
+
// 2. RN module state with known mutation APIs (Dimensions.set) — restored
|
|
32
|
+
// from a boot-time snapshot (value-restore: no attribution needed).
|
|
33
|
+
// 2b. process.env — restored to the last bless() snapshot.
|
|
34
|
+
// 3. RNTL trees left mounted — RNTL is resident too, so its auto-cleanup
|
|
35
|
+
// afterEach (registered during the first file) never re-registers for
|
|
36
|
+
// later files; cleanup() is called explicitly.
|
|
37
|
+
// 4. Boundary/preset mocks that registered callbacks in
|
|
38
|
+
// globalThis.__vitest_native_resets (none are stateful today; the
|
|
39
|
+
// registry is the extension point).
|
|
40
|
+
// 5. globalThis keys added during the previous TEST phase — deleted. The
|
|
41
|
+
// baseline starts at the first per-file call (after Vitest injected its
|
|
42
|
+
// per-batch globals) and grows at every bless(). Mutations of
|
|
43
|
+
// pre-existing keys are not restored (documented v1 limitation).
|
|
44
|
+
import { createRequire } from "node:module";
|
|
45
|
+
import path from "node:path";
|
|
46
|
+
|
|
47
|
+
// Keys owned by the harness or this plugin — never deleted by the globals diff.
|
|
48
|
+
const PRESERVED_GLOBALS = /^(__vitest|__VITEST|__coverage__|__VITE)/;
|
|
49
|
+
// Vitest-managed env keys change per task; leave them alone.
|
|
50
|
+
const ENV_PRESERVED = /^VITEST_/;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Called once at hot-worker boot, AFTER react-native has been preloaded and its
|
|
54
|
+
* stateful core modules touched (so their internal boot-time listeners register
|
|
55
|
+
* before the tracking wrapper installs). Returns { hotReset, bless }:
|
|
56
|
+
* hotReset is invoked by setup.mjs at the top of every file; bless by
|
|
57
|
+
* runner.mjs between a file's import phase and its first test.
|
|
58
|
+
*/
|
|
59
|
+
export function installHotReset({ projectRoot, diagnostics }) {
|
|
60
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
61
|
+
const RN = req("react-native");
|
|
62
|
+
|
|
63
|
+
// --- (1) Track listeners added to the RCTDeviceEventEmitter singleton ---
|
|
64
|
+
const tracked = new Set();
|
|
65
|
+
const emitter = RN.DeviceEventEmitter;
|
|
66
|
+
const origAddListener = emitter.addListener.bind(emitter);
|
|
67
|
+
emitter.addListener = (type, listener, context) => {
|
|
68
|
+
const sub = origAddListener(type, listener, context);
|
|
69
|
+
tracked.add(sub);
|
|
70
|
+
return sub;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// --- (2) Boot snapshot of mutable resident RN state ---
|
|
74
|
+
let dims = null;
|
|
75
|
+
try {
|
|
76
|
+
dims = {
|
|
77
|
+
window: { ...RN.Dimensions.get("window") },
|
|
78
|
+
screen: { ...RN.Dimensions.get("screen") },
|
|
79
|
+
};
|
|
80
|
+
} catch {}
|
|
81
|
+
|
|
82
|
+
// --- (2b) process.env snapshot, refreshed at every bless() ---
|
|
83
|
+
let envBaseline = { ...process.env };
|
|
84
|
+
|
|
85
|
+
// --- (5) globalThis baseline: starts at the first per-file call, grows at
|
|
86
|
+
// every bless() ---
|
|
87
|
+
let globalBaseline = null;
|
|
88
|
+
|
|
89
|
+
// Attribution-dependent teardowns run only once bless() has fired at least
|
|
90
|
+
// once (i.e. the hot runner is installed and working).
|
|
91
|
+
let armed = false;
|
|
92
|
+
|
|
93
|
+
function bless() {
|
|
94
|
+
armed = true;
|
|
95
|
+
if (globalBaseline) {
|
|
96
|
+
for (const key of Reflect.ownKeys(globalThis)) globalBaseline.add(key);
|
|
97
|
+
}
|
|
98
|
+
envBaseline = { ...process.env };
|
|
99
|
+
// Import-phase subscriptions are legitimate resident state — stop tracking.
|
|
100
|
+
tracked.clear();
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function hotReset() {
|
|
104
|
+
if (globalBaseline === null) {
|
|
105
|
+
// First file: nothing to clean — the worker is pristine. Capture the
|
|
106
|
+
// baseline every later file must be reset back to.
|
|
107
|
+
globalBaseline = new Set(Reflect.ownKeys(globalThis));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// (3) RNTL cleanup happens in setup.mjs, NOT here: it must run in the
|
|
112
|
+
// module-runner context so it reaches the SAME RNTL instance the tests
|
|
113
|
+
// use. Loading RNTL through Node from here created a second instance whose
|
|
114
|
+
// act/auto-cleanup machinery corrupted rendering for every later file
|
|
115
|
+
// when the consumer's graph inlines RNTL (found via Rocket.Chat).
|
|
116
|
+
|
|
117
|
+
// (2) Restore mutable resident RN state (value-restore, always safe).
|
|
118
|
+
if (dims) {
|
|
119
|
+
try {
|
|
120
|
+
RN.Dimensions.set(dims);
|
|
121
|
+
} catch {}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// (4) Boundary/preset mock reset callbacks.
|
|
125
|
+
const resets = globalThis.__vitest_native_resets;
|
|
126
|
+
if (Array.isArray(resets)) {
|
|
127
|
+
for (const fn of resets) {
|
|
128
|
+
try {
|
|
129
|
+
fn();
|
|
130
|
+
} catch {}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (!armed) return; // no bless yet → cannot attribute; fail open
|
|
135
|
+
|
|
136
|
+
// (1) Remove the previous file's test-phase RN event listeners.
|
|
137
|
+
for (const sub of tracked) {
|
|
138
|
+
try {
|
|
139
|
+
sub.remove();
|
|
140
|
+
} catch {}
|
|
141
|
+
}
|
|
142
|
+
tracked.clear();
|
|
143
|
+
|
|
144
|
+
// (2b) Restore process.env to the last bless() snapshot.
|
|
145
|
+
for (const key of Object.keys(process.env)) {
|
|
146
|
+
if (ENV_PRESERVED.test(key)) continue;
|
|
147
|
+
if (!(key in envBaseline)) delete process.env[key];
|
|
148
|
+
else if (process.env[key] !== envBaseline[key]) process.env[key] = envBaseline[key];
|
|
149
|
+
}
|
|
150
|
+
for (const key of Object.keys(envBaseline)) {
|
|
151
|
+
if (!(key in process.env) && !ENV_PRESERVED.test(key)) process.env[key] = envBaseline[key];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// (5) Delete globals added during the previous test phase.
|
|
155
|
+
const deleted = [];
|
|
156
|
+
for (const key of Reflect.ownKeys(globalThis)) {
|
|
157
|
+
if (globalBaseline.has(key)) continue;
|
|
158
|
+
if (typeof key === "string" && PRESERVED_GLOBALS.test(key)) continue;
|
|
159
|
+
try {
|
|
160
|
+
delete globalThis[key];
|
|
161
|
+
if (diagnostics) deleted.push(String(key));
|
|
162
|
+
} catch {}
|
|
163
|
+
}
|
|
164
|
+
if (diagnostics && deleted.length) {
|
|
165
|
+
console.log(`[vitest-native] hot reset: deleted test-phase globals: ${deleted.join(", ")}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return { hotReset, bless };
|
|
170
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Metro-style platform-extension resolution: prefer .ios.js / .native.js over .js,
|
|
2
|
+
// and fall back to a directory index. Shared by the require hook and the loader.
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
const EXTS = [".ios.js", ".native.js", ".js"];
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Given an absolute base path with no extension (e.g. ".../Foo"), return the
|
|
10
|
+
* first existing platform variant (".../Foo.ios.js", etc.) or directory index,
|
|
11
|
+
* or null if none exist.
|
|
12
|
+
*/
|
|
13
|
+
export function resolvePlatformFile(absBase) {
|
|
14
|
+
for (const ext of EXTS) {
|
|
15
|
+
if (fs.existsSync(absBase + ext)) return absBase + ext;
|
|
16
|
+
}
|
|
17
|
+
for (const ext of EXTS) {
|
|
18
|
+
const idx = path.join(absBase, "index" + ext);
|
|
19
|
+
if (fs.existsSync(idx)) return idx;
|
|
20
|
+
}
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Hot-runtime test runner (wired as `test.runner` by the plugin when
|
|
2
|
+
// hotRuntime is on). One job: tell reset.mjs where a file's IMPORT phase ends.
|
|
3
|
+
//
|
|
4
|
+
// startTests (per file, because Vitest's worker loop calls it with one file at
|
|
5
|
+
// a time) runs: onBeforeCollect → collectTests (imports setup + the test module
|
|
6
|
+
// and, transitively, any resident externalized deps) → onBeforeRunFiles →
|
|
7
|
+
// tests. So onBeforeRunFiles is the exact boundary between import-phase state
|
|
8
|
+
// (resident-library lazy init — must be preserved across files, it never
|
|
9
|
+
// re-runs) and test-phase state (pollution the next file's reset removes).
|
|
10
|
+
// See reset.mjs for the full attribution model.
|
|
11
|
+
import { VitestTestRunner } from "vitest/runners";
|
|
12
|
+
|
|
13
|
+
export default class NativeHotRunner extends VitestTestRunner {
|
|
14
|
+
async onBeforeRunFiles(files) {
|
|
15
|
+
globalThis.__vitest_native_hot_bless?.();
|
|
16
|
+
return super.onBeforeRunFiles?.(files);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Native-engine setup file (injected into test.setupFiles by the plugin). Installs
|
|
2
|
+
// globals, registers the ESM loader hook, installs the CJS require hooks, and
|
|
3
|
+
// builds any third-party preset mocks the project uses.
|
|
4
|
+
import { createRequire, register } from "node:module";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { expect, vi } from "vitest";
|
|
7
|
+
import { installGlobals } from "./globals.mjs";
|
|
8
|
+
import { installRequireHooks } from "./hooks.mjs";
|
|
9
|
+
import * as presetFactories from "../presets.mjs";
|
|
10
|
+
|
|
11
|
+
// Hot runtime: surgical reset of state left by the PREVIOUS file. Setup files
|
|
12
|
+
// are force-inlined by Vitest, so this body re-runs per test file even when the
|
|
13
|
+
// rest of this package is externalized — making it the per-file hook. Installed
|
|
14
|
+
// by worker.mjs (hot runtime only); a no-op everywhere else.
|
|
15
|
+
if (globalThis.__vitest_native_hot_reset) {
|
|
16
|
+
// Vitest-level state first: in a fresh-worker-per-file world these die with
|
|
17
|
+
// the worker, but Vitest's own per-file loop never undoes them. Fake timers
|
|
18
|
+
// are the big one — jest suites enable them per file and rely on teardown;
|
|
19
|
+
// leaked into the next file they break React rendering entirely ("Can't
|
|
20
|
+
// access .root on unmounted test renderer" via RNTL).
|
|
21
|
+
vi.useRealTimers();
|
|
22
|
+
vi.unstubAllGlobals();
|
|
23
|
+
vi.unstubAllEnvs();
|
|
24
|
+
// NOTE on RNTL trees: when RNTL is inlined in the consumer graph it
|
|
25
|
+
// re-evaluates per file (fresh registry + fresh auto-cleanup) and needs no
|
|
26
|
+
// help. When RNTL is externalized/resident, trees from earlier files can
|
|
27
|
+
// stay mounted (auto-cleanup's afterEach only registers in the first file) —
|
|
28
|
+
// a memory accumulation, bounded by worker recycling, NOT a correctness
|
|
29
|
+
// leak (each file renders into fresh roots; cross-file listeners are removed
|
|
30
|
+
// by the reset below). Do NOT "fix" this by importing RNTL here or via Node
|
|
31
|
+
// require — both create instance/evaluation-order hazards that corrupt
|
|
32
|
+
// rendering (found via Rocket.Chat).
|
|
33
|
+
globalThis.__vitest_native_hot_reset();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
|
|
37
|
+
const diagnostics = process.env.VITEST_NATIVE_DIAGNOSTICS === "true";
|
|
38
|
+
// Extra node_modules packages to transform (from the plugin's `transform` option).
|
|
39
|
+
let transformPkgs = [];
|
|
40
|
+
try {
|
|
41
|
+
if (process.env.VITEST_NATIVE_TRANSFORM)
|
|
42
|
+
transformPkgs = JSON.parse(process.env.VITEST_NATIVE_TRANSFORM);
|
|
43
|
+
} catch {}
|
|
44
|
+
|
|
45
|
+
// --- Third-party preset mocks ---
|
|
46
|
+
//
|
|
47
|
+
// Native-runtime libraries (Reanimated's worklets, gesture-handler natives, …)
|
|
48
|
+
// cannot execute in Node, so the native engine shadows them with the same
|
|
49
|
+
// self-contained mocks the mock engine uses. The plugin resolves which presets
|
|
50
|
+
// are active (sync, from installed packages) and passes their names here.
|
|
51
|
+
//
|
|
52
|
+
// Redirection happens in three places that must agree:
|
|
53
|
+
// 1. the Vite plugin's resolveId/load (the app/test graph's direct imports),
|
|
54
|
+
// 2. the ESM loader hook (bare imports reaching Node, incl. nested inside
|
|
55
|
+
// externalized third-party libs),
|
|
56
|
+
// 3. the CJS require hook (nested require() from externalized libs).
|
|
57
|
+
// All three read the mock object from globalThis.__vitest_native_preset_mocks
|
|
58
|
+
// (populated below). (2) and (3) close the gap where a third-party library pulls
|
|
59
|
+
// in a preset package itself — those requests never reach Vite.
|
|
60
|
+
let presetNames = [];
|
|
61
|
+
try {
|
|
62
|
+
if (process.env.VITEST_NATIVE_PRESET_NAMES)
|
|
63
|
+
presetNames = JSON.parse(process.env.VITEST_NATIVE_PRESET_NAMES);
|
|
64
|
+
} catch {}
|
|
65
|
+
|
|
66
|
+
// Discover preset module (package) names + their static export lists WITHOUT
|
|
67
|
+
// building the mocks yet — building can lazily touch react-native, so the require
|
|
68
|
+
// hooks must be installed first.
|
|
69
|
+
const presetDefs = []; // [{ pkg, mod, presetName }]
|
|
70
|
+
const presetExports = {}; // pkg -> string[] (named exports, for the ESM loader)
|
|
71
|
+
for (const name of presetNames) {
|
|
72
|
+
const factory = presetFactories[name];
|
|
73
|
+
if (typeof factory !== "function") continue;
|
|
74
|
+
const preset = factory();
|
|
75
|
+
for (const [pkg, mod] of Object.entries(preset.modules)) {
|
|
76
|
+
presetDefs.push({ pkg, mod, presetName: preset.name });
|
|
77
|
+
presetExports[pkg] = mod.exports || [];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
installGlobals();
|
|
82
|
+
// register() once per WORKER, not per file: under the hot runtime this setup
|
|
83
|
+
// file re-evaluates per test file in a persistent worker, and re-registering
|
|
84
|
+
// would stack a new loader-hook layer on every file. (installGlobals and
|
|
85
|
+
// installRequireHooks are internally guarded the same way.)
|
|
86
|
+
if (!globalThis.__vitest_native_loader_registered) {
|
|
87
|
+
globalThis.__vitest_native_loader_registered = true;
|
|
88
|
+
register("./loader.mjs", import.meta.url, {
|
|
89
|
+
data: { projectRoot, transformPkgs, presetExports },
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
installRequireHooks(projectRoot, transformPkgs);
|
|
93
|
+
|
|
94
|
+
// Build the mock objects now that the require hooks are installed (preset
|
|
95
|
+
// factories may lazily resolve react-native at render time).
|
|
96
|
+
const g = globalThis;
|
|
97
|
+
g.__vitest_native_preset_mocks = g.__vitest_native_preset_mocks || {};
|
|
98
|
+
for (const { pkg, mod, presetName } of presetDefs) {
|
|
99
|
+
g.__vitest_native_preset_mocks[pkg] = mod.factory();
|
|
100
|
+
if (diagnostics) {
|
|
101
|
+
console.log(`[vitest-native] (native) registered preset mock: ${pkg} (${presetName})`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// --- RNTL built-in matchers (toBeOnTheScreen, toBeDisabled, toHaveStyle, …) ---
|
|
106
|
+
// The mock engine's setup registers these; the native engine must too, or
|
|
107
|
+
// `engine:'native'` users have no jest-native/RNTL matchers (and a jest-compat
|
|
108
|
+
// migration is worse off — jestCompatAliases no-ops its extend-expect on the
|
|
109
|
+
// promise that vitest-native registers them). Caught by the differential cross-check.
|
|
110
|
+
try {
|
|
111
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
112
|
+
const matchers = req("@testing-library/react-native/build/matchers");
|
|
113
|
+
const fns = {};
|
|
114
|
+
for (const [k, v] of Object.entries(matchers || {})) {
|
|
115
|
+
if (typeof v === "function" && k !== "__esModule") fns[k] = v;
|
|
116
|
+
}
|
|
117
|
+
if (Object.keys(fns).length > 0) {
|
|
118
|
+
expect.extend(fns);
|
|
119
|
+
if (diagnostics) {
|
|
120
|
+
console.log(`[vitest-native] (native) registered ${Object.keys(fns).length} RNTL matchers`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
} catch (e) {
|
|
124
|
+
if (diagnostics) {
|
|
125
|
+
console.log(`[vitest-native] (native) could not load RNTL matchers: ${e?.message}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// NOTE: the cosmetic React "update to LogBoxStateSubscription not wrapped in
|
|
130
|
+
// act()" warning (which used to appear on every interaction) is fixed at the
|
|
131
|
+
// source — the native boundary stubs LogBoxNotificationContainer (the dev UI
|
|
132
|
+
// AppContainer mounts) to render null, so LogBoxStateSubscription never mounts
|
|
133
|
+
// and never schedules its out-of-act setState. See boundary.mjs + the regression
|
|
134
|
+
// test tests-native/logbox-act.test.tsx.
|