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.
Files changed (54) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +268 -9
  3. package/dist/chunk-CZWwpsFl.cjs +43 -0
  4. package/dist/helpers.cjs +10 -0
  5. package/dist/helpers.d.cts +7 -1
  6. package/dist/helpers.d.mts +7 -1
  7. package/dist/helpers.mjs +10 -1
  8. package/dist/{index-CJqS-y_M.d.cts → index-CJIhukN_.d.mts} +58 -4
  9. package/dist/{index-h4vpIkQO.d.mts → index-DEB7OFaJ.d.cts} +60 -2
  10. package/dist/index.cjs +296 -35
  11. package/dist/index.d.cts +1 -1
  12. package/dist/index.d.mts +1 -1
  13. package/dist/index.mjs +292 -33
  14. package/dist/jest-compat/interop.mjs +30 -0
  15. package/dist/jest-compat/jest-globals.d.mts +3 -0
  16. package/dist/jest-compat/jest-globals.mjs +9 -0
  17. package/dist/jest-compat/noop.d.mts +3 -0
  18. package/dist/jest-compat/noop.mjs +7 -0
  19. package/dist/jest-compat/setup.d.mts +3 -0
  20. package/dist/jest-compat/setup.mjs +41 -0
  21. package/dist/jest-compat.cjs +109 -0
  22. package/dist/jest-compat.d.cts +38 -0
  23. package/dist/jest-compat.d.mts +38 -0
  24. package/dist/jest-compat.mjs +104 -0
  25. package/dist/matchers.cjs +69 -0
  26. package/dist/matchers.d.cts +51 -0
  27. package/dist/matchers.d.mts +51 -0
  28. package/dist/matchers.mjs +66 -0
  29. package/dist/native/boundary.mjs +225 -0
  30. package/dist/native/globals.mjs +112 -0
  31. package/dist/native/hooks.mjs +85 -0
  32. package/dist/native/loader.mjs +123 -0
  33. package/dist/native/match.mjs +9 -0
  34. package/dist/native/reset.mjs +170 -0
  35. package/dist/native/resolve.mjs +22 -0
  36. package/dist/native/runner.mjs +18 -0
  37. package/dist/native/setup.mjs +134 -0
  38. package/dist/native/transform.mjs +79 -0
  39. package/dist/native/worker.mjs +96 -0
  40. package/dist/pool-B4mWN3N5.cjs +60 -0
  41. package/dist/pool-oPTZiSXU.mjs +58 -0
  42. package/dist/{preset-map-Bt4dXkZO.cjs → preset-map-C3jxnkiX.cjs} +6 -1
  43. package/dist/{preset-map-D224CC5w.mjs → preset-map-OJm5IWuL.mjs} +6 -1
  44. package/dist/{presets-9Y4ssfiH.cjs → presets-2I68Ipyl.cjs} +768 -122
  45. package/dist/{presets-CWH0gtM0.mjs → presets-DOGXQzYT.mjs} +732 -87
  46. package/dist/presets.cjs +5 -1
  47. package/dist/presets.d.cts +2 -2
  48. package/dist/presets.d.mts +2 -2
  49. package/dist/presets.mjs +2 -2
  50. package/dist/setup.cjs +903 -121
  51. package/dist/setup.mjs +899 -118
  52. package/docs/migrating-from-jest.md +123 -0
  53. package/docs/migrating-from-vitest-react-native.md +109 -0
  54. package/package.json +67 -8
@@ -0,0 +1,79 @@
1
+ // Flow-strips a React Native source file via the project's @react-native/babel-preset
2
+ // (the only transformer that lowers RN's `component` syntax). Disk-cached by
3
+ // path + mtime + size + preset version. Used by BOTH the loader hook (import) and
4
+ // the require hook — they run in separate threads, so this module is stateless.
5
+ import { createRequire } from "node:module";
6
+ import path from "node:path";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import crypto from "node:crypto";
10
+
11
+ let _babel;
12
+ let _preset;
13
+ let _cacheDir;
14
+ let _writeSeq = 0;
15
+ const mem = new Map();
16
+
17
+ function init(projectRoot) {
18
+ if (_babel) return;
19
+ const req = createRequire(path.join(projectRoot, "package.json"));
20
+ try {
21
+ _babel = req("@babel/core");
22
+ _preset = req.resolve("@react-native/babel-preset");
23
+ } catch {
24
+ throw new Error(
25
+ "[vitest-native] engine 'native' requires '@react-native/babel-preset' and " +
26
+ "'@babel/core' in your project. Install them as devDependencies " +
27
+ "(they ship with React Native projects by default).",
28
+ );
29
+ }
30
+ const presetVersion = req("@react-native/babel-preset/package.json").version;
31
+ _cacheDir = path.join(os.tmpdir(), "vitest-native-cache", presetVersion);
32
+ fs.mkdirSync(_cacheDir, { recursive: true });
33
+ }
34
+
35
+ /** Returns true if the source contains RN Flow syntax that must be transformed. */
36
+ export function isFlow(src) {
37
+ return /@flow|import typeof|\bcomponent\s+\w/.test(src);
38
+ }
39
+
40
+ /** Transform an RN source file to runnable CJS. Cached in-memory + on disk. */
41
+ export function transformRN(file, src, projectRoot) {
42
+ init(projectRoot);
43
+ const memHit = mem.get(file);
44
+ if (memHit !== undefined) return memHit;
45
+
46
+ const st = fs.statSync(file);
47
+ const key = crypto
48
+ .createHash("sha1")
49
+ .update(file + ":" + st.mtimeMs + ":" + st.size)
50
+ .digest("hex");
51
+ const cachePath = path.join(_cacheDir, key + ".js");
52
+ try {
53
+ const cached = fs.readFileSync(cachePath, "utf8");
54
+ mem.set(file, cached);
55
+ return cached;
56
+ } catch {}
57
+
58
+ const out = _babel.transformSync(src, {
59
+ filename: file,
60
+ presets: [_preset],
61
+ babelrc: false,
62
+ configFile: false,
63
+ caller: { name: "metro", bundler: "metro", platform: "ios", supportsStaticESM: false },
64
+ }).code;
65
+ // Atomic write: multiple worker threads may transform the same RN file
66
+ // concurrently on a cold cache. Write to a unique temp file then rename
67
+ // (atomic on POSIX same-dir) so a concurrent reader never sees a partial file.
68
+ const tmp = `${cachePath}.${process.pid}.${_writeSeq++}.tmp`;
69
+ try {
70
+ fs.writeFileSync(tmp, out);
71
+ fs.renameSync(tmp, cachePath);
72
+ } catch {
73
+ try {
74
+ fs.rmSync(tmp, { force: true });
75
+ } catch {}
76
+ }
77
+ mem.set(file, out);
78
+ return out;
79
+ }
@@ -0,0 +1,96 @@
1
+ // Hot-runtime worker entry for the native engine (loaded by pool.ts's
2
+ // NativePoolWorker instead of Vitest's stock dist/workers/threads.js).
3
+ //
4
+ // The keystone: "schedule like isolate:false, reset like isolate:true."
5
+ // The pool runs with isolate:false so the scheduler keeps this worker alive
6
+ // across test files — externalized React Native loads once into the thread's
7
+ // Node require cache and stays resident. Vitest's own per-file isolation
8
+ // (mocker.reset + module-runner resetModules, inside its run() loop) is gated
9
+ // on config.isolate, so we flip it back to true here, worker-side, after the
10
+ // scheduling decision has already been made. Result: fresh user modules per
11
+ // file, hot RN graph.
12
+ import { createRequire } from "node:module";
13
+ import path from "node:path";
14
+ import { isMainThread, parentPort, threadId } from "node:worker_threads";
15
+ import { init, runBaseTests, setupEnvironment } from "vitest/worker";
16
+ import { installGlobals } from "./globals.mjs";
17
+ import { installRequireHooks } from "./hooks.mjs";
18
+ import { installHotReset } from "./reset.mjs";
19
+
20
+ if (isMainThread || !parentPort) {
21
+ throw new Error("[vitest-native] hot worker entry must run in node:worker_threads");
22
+ }
23
+
24
+ const projectRoot = process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd();
25
+ const diagnostics = process.env.VITEST_NATIVE_DIAGNOSTICS === "true";
26
+ let transformPkgs = [];
27
+ try {
28
+ if (process.env.VITEST_NATIVE_TRANSFORM)
29
+ transformPkgs = JSON.parse(process.env.VITEST_NATIVE_TRANSFORM);
30
+ } catch {}
31
+
32
+ if (diagnostics) {
33
+ // One line per worker boot: under a hot pool, N files sharing a worker print
34
+ // this once, not N times — the "RN loads once" proof.
35
+ console.log(`[vitest-native] hot worker boot (pid ${process.pid}, tid ${threadId})`);
36
+ }
37
+
38
+ // --- One-time worker init: load RN into the resident Node require cache ---
39
+ // The setup file repeats these installs per file, but they are globalThis-
40
+ // guarded; doing them at boot lets RN preload BEFORE the globals baseline and
41
+ // listener tracking in reset.mjs, so RN's own boot state is preserved across
42
+ // per-file resets rather than wrongly torn down with test pollution.
43
+ installGlobals();
44
+ installRequireHooks(projectRoot, transformPkgs);
45
+ try {
46
+ const req = createRequire(path.join(projectRoot, "package.json"));
47
+ const RN = req("react-native");
48
+ // RN's index is lazy getters — touch the stateful core modules now so any
49
+ // internal boot-time listeners register before reset.mjs starts tracking.
50
+ for (const name of [
51
+ "DeviceEventEmitter",
52
+ "Dimensions",
53
+ "Platform",
54
+ "AppState",
55
+ "Appearance",
56
+ "Keyboard",
57
+ "Linking",
58
+ "I18nManager",
59
+ "InteractionManager",
60
+ "PixelRatio",
61
+ "StyleSheet",
62
+ ]) {
63
+ try {
64
+ void RN[name];
65
+ } catch {}
66
+ }
67
+ } catch (error) {
68
+ throw new Error(
69
+ `[vitest-native] hot worker failed to preload react-native from ${projectRoot}: ${error?.message}`,
70
+ { cause: error },
71
+ );
72
+ }
73
+ const { hotReset, bless } = installHotReset({ projectRoot, diagnostics });
74
+ globalThis.__vitest_native_hot_reset = hotReset; // invoked by setup.mjs per file
75
+ globalThis.__vitest_native_hot_bless = bless; // invoked by runner.mjs after each import phase
76
+
77
+ function runWithPerFileIsolation(method) {
78
+ return (state, traces) => {
79
+ // Vitest's worker-side per-file reset clears only the module-runner graph;
80
+ // externalized RN in the Node require cache is untouched — exactly the
81
+ // "fresh user modules, resident RN" split the native engine needs.
82
+ state.ctx.config.isolate = true;
83
+ return runBaseTests(method, state, traces);
84
+ };
85
+ }
86
+
87
+ init({
88
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin -- worker_threads MessagePort, not window
89
+ post: (msg) => parentPort.postMessage(msg),
90
+ on: (callback) => parentPort.on("message", callback),
91
+ off: (callback) => parentPort.off("message", callback),
92
+ teardown: () => parentPort.removeAllListeners("message"),
93
+ runTests: runWithPerFileIsolation("run"),
94
+ collectTests: runWithPerFileIsolation("collect"),
95
+ setup: setupEnvironment,
96
+ });
@@ -0,0 +1,60 @@
1
+ const require_chunk = require("./chunk-CZWwpsFl.cjs");
2
+ let node_path = require("node:path");
3
+ node_path = require_chunk.__toESM(node_path);
4
+ let vitest_node = require("vitest/node");
5
+ //#region src/native/pool.ts
6
+ function deepEqual(a, b) {
7
+ if (a === b) return true;
8
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
9
+ const ka = Object.keys(a);
10
+ const kb = Object.keys(b);
11
+ if (ka.length !== kb.length) return false;
12
+ return ka.every((k) => kb.includes(k) && deepEqual(a[k], b[k]));
13
+ }
14
+ var NativePoolWorker = class extends vitest_node.ThreadsPoolWorker {
15
+ name = "vitest-native";
16
+ reportMemory;
17
+ entrypoint;
18
+ environment;
19
+ recycleAfterFiles;
20
+ memoryLimit;
21
+ filesRun = 0;
22
+ lastHeapUsed = 0;
23
+ memoryListenerAttached = false;
24
+ constructor(options, native) {
25
+ super(options);
26
+ this.entrypoint = node_path.default.resolve(native.workerEntry);
27
+ this.environment = options.environment;
28
+ this.recycleAfterFiles = native.recycleAfterFiles ?? 0;
29
+ this.memoryLimit = native.memoryLimit ?? 0;
30
+ this.reportMemory = this.memoryLimit > 0;
31
+ }
32
+ async start() {
33
+ await super.start();
34
+ if (this.reportMemory && !this.memoryListenerAttached) {
35
+ this.memoryListenerAttached = true;
36
+ this.on("message", (message) => {
37
+ if (message?.__vitest_worker_response__ && typeof message.usedMemory === "number") this.lastHeapUsed = message.usedMemory;
38
+ });
39
+ }
40
+ }
41
+ send(message) {
42
+ if (message.type === "run" || message.type === "collect") this.filesRun += message.context.files.length;
43
+ super.send(message);
44
+ }
45
+ canReuse(task) {
46
+ if (this.recycleAfterFiles > 0 && this.filesRun >= this.recycleAfterFiles) return false;
47
+ if (this.memoryLimit > 0 && this.lastHeapUsed >= this.memoryLimit) return false;
48
+ const env = task.context.environment;
49
+ return env.name === this.environment.name && deepEqual(env.options, this.environment.options);
50
+ }
51
+ };
52
+ /** Pool initializer for `test.pool` — keeps RN-hot workers alive across files. */
53
+ function nativePool(options) {
54
+ return {
55
+ name: "vitest-native",
56
+ createPoolWorker: (poolOptions) => new NativePoolWorker(poolOptions, options)
57
+ };
58
+ }
59
+ //#endregion
60
+ exports.nativePool = nativePool;
@@ -0,0 +1,58 @@
1
+ import path from "node:path";
2
+ import { ThreadsPoolWorker } from "vitest/node";
3
+ //#region src/native/pool.ts
4
+ function deepEqual(a, b) {
5
+ if (a === b) return true;
6
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
7
+ const ka = Object.keys(a);
8
+ const kb = Object.keys(b);
9
+ if (ka.length !== kb.length) return false;
10
+ return ka.every((k) => kb.includes(k) && deepEqual(a[k], b[k]));
11
+ }
12
+ var NativePoolWorker = class extends ThreadsPoolWorker {
13
+ name = "vitest-native";
14
+ reportMemory;
15
+ entrypoint;
16
+ environment;
17
+ recycleAfterFiles;
18
+ memoryLimit;
19
+ filesRun = 0;
20
+ lastHeapUsed = 0;
21
+ memoryListenerAttached = false;
22
+ constructor(options, native) {
23
+ super(options);
24
+ this.entrypoint = path.resolve(native.workerEntry);
25
+ this.environment = options.environment;
26
+ this.recycleAfterFiles = native.recycleAfterFiles ?? 0;
27
+ this.memoryLimit = native.memoryLimit ?? 0;
28
+ this.reportMemory = this.memoryLimit > 0;
29
+ }
30
+ async start() {
31
+ await super.start();
32
+ if (this.reportMemory && !this.memoryListenerAttached) {
33
+ this.memoryListenerAttached = true;
34
+ this.on("message", (message) => {
35
+ if (message?.__vitest_worker_response__ && typeof message.usedMemory === "number") this.lastHeapUsed = message.usedMemory;
36
+ });
37
+ }
38
+ }
39
+ send(message) {
40
+ if (message.type === "run" || message.type === "collect") this.filesRun += message.context.files.length;
41
+ super.send(message);
42
+ }
43
+ canReuse(task) {
44
+ if (this.recycleAfterFiles > 0 && this.filesRun >= this.recycleAfterFiles) return false;
45
+ if (this.memoryLimit > 0 && this.lastHeapUsed >= this.memoryLimit) return false;
46
+ const env = task.context.environment;
47
+ return env.name === this.environment.name && deepEqual(env.options, this.environment.options);
48
+ }
49
+ };
50
+ /** Pool initializer for `test.pool` — keeps RN-hot workers alive across files. */
51
+ function nativePool(options) {
52
+ return {
53
+ name: "vitest-native",
54
+ createPoolWorker: (poolOptions) => new NativePoolWorker(poolOptions, options)
55
+ };
56
+ }
57
+ //#endregion
58
+ export { nativePool };
@@ -11,9 +11,14 @@ const AUTO_DETECT_PRESETS = {
11
11
  "@react-navigation/native-stack": "navigation",
12
12
  "@react-navigation/bottom-tabs": "navigation",
13
13
  "@react-navigation/elements": "navigation",
14
+ "@react-navigation/drawer": "navigation",
14
15
  "@react-native-async-storage/async-storage": "asyncStorage",
15
16
  "react-native-screens": "screens",
16
- "expo-constants": "expo"
17
+ "expo-constants": "expo",
18
+ "react-native-device-info": "deviceInfo",
19
+ "react-native-mmkv": "mmkv",
20
+ "react-native-svg": "svg",
21
+ "react-native-webview": "webview"
17
22
  };
18
23
  //#endregion
19
24
  Object.defineProperty(exports, "AUTO_DETECT_PRESETS", {
@@ -11,9 +11,14 @@ const AUTO_DETECT_PRESETS = {
11
11
  "@react-navigation/native-stack": "navigation",
12
12
  "@react-navigation/bottom-tabs": "navigation",
13
13
  "@react-navigation/elements": "navigation",
14
+ "@react-navigation/drawer": "navigation",
14
15
  "@react-native-async-storage/async-storage": "asyncStorage",
15
16
  "react-native-screens": "screens",
16
- "expo-constants": "expo"
17
+ "expo-constants": "expo",
18
+ "react-native-device-info": "deviceInfo",
19
+ "react-native-mmkv": "mmkv",
20
+ "react-native-svg": "svg",
21
+ "react-native-webview": "webview"
17
22
  };
18
23
  //#endregion
19
24
  export { AUTO_DETECT_PRESETS as t };