vitest-native 0.3.0 → 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 (50) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +240 -11
  3. package/dist/chunk-CZWwpsFl.cjs +43 -0
  4. package/dist/{index-CJqS-y_M.d.cts → index-CJIhukN_.d.mts} +58 -4
  5. package/dist/{index-h4vpIkQO.d.mts → index-DEB7OFaJ.d.cts} +60 -2
  6. package/dist/index.cjs +252 -21
  7. package/dist/index.d.cts +1 -1
  8. package/dist/index.d.mts +1 -1
  9. package/dist/index.mjs +248 -18
  10. package/dist/jest-compat/interop.mjs +30 -0
  11. package/dist/jest-compat/jest-globals.d.mts +3 -0
  12. package/dist/jest-compat/jest-globals.mjs +9 -0
  13. package/dist/jest-compat/noop.d.mts +3 -0
  14. package/dist/jest-compat/noop.mjs +7 -0
  15. package/dist/jest-compat/setup.d.mts +3 -0
  16. package/dist/jest-compat/setup.mjs +41 -0
  17. package/dist/jest-compat.cjs +109 -0
  18. package/dist/jest-compat.d.cts +38 -0
  19. package/dist/jest-compat.d.mts +38 -0
  20. package/dist/jest-compat.mjs +104 -0
  21. package/dist/matchers.cjs +69 -0
  22. package/dist/matchers.d.cts +51 -0
  23. package/dist/matchers.d.mts +51 -0
  24. package/dist/matchers.mjs +66 -0
  25. package/dist/native/boundary.mjs +225 -0
  26. package/dist/native/globals.mjs +112 -0
  27. package/dist/native/hooks.mjs +85 -0
  28. package/dist/native/loader.mjs +123 -0
  29. package/dist/native/match.mjs +9 -0
  30. package/dist/native/reset.mjs +170 -0
  31. package/dist/native/resolve.mjs +22 -0
  32. package/dist/native/runner.mjs +18 -0
  33. package/dist/native/setup.mjs +134 -0
  34. package/dist/native/transform.mjs +79 -0
  35. package/dist/native/worker.mjs +96 -0
  36. package/dist/pool-B4mWN3N5.cjs +60 -0
  37. package/dist/pool-oPTZiSXU.mjs +58 -0
  38. package/dist/{preset-map-DxU6UgYS.cjs → preset-map-C3jxnkiX.cjs} +5 -1
  39. package/dist/{preset-map-BTpoNH3G.mjs → preset-map-OJm5IWuL.mjs} +5 -1
  40. package/dist/{presets-B-spxZz7.cjs → presets-2I68Ipyl.cjs} +437 -41
  41. package/dist/{presets-DvrcfEPz.mjs → presets-DOGXQzYT.mjs} +401 -6
  42. package/dist/presets.cjs +5 -1
  43. package/dist/presets.d.cts +2 -2
  44. package/dist/presets.d.mts +2 -2
  45. package/dist/presets.mjs +2 -2
  46. package/dist/setup.cjs +263 -115
  47. package/dist/setup.mjs +259 -112
  48. package/docs/migrating-from-jest.md +123 -0
  49. package/docs/migrating-from-vitest-react-native.md +109 -0
  50. package/package.json +65 -9
package/dist/setup.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { n as __require } from "./chunk-CjcI7cDX.mjs";
2
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-BTpoNH3G.mjs";
3
- import { t as presets_exports } from "./presets-DvrcfEPz.mjs";
2
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-OJm5IWuL.mjs";
3
+ import { f as createPressableMock, p as buildPressableHostProps, t as presets_exports } from "./presets-DOGXQzYT.mjs";
4
4
  import { serializer } from "./serializer.mjs";
5
+ import { animatedMatchers } from "./matchers.mjs";
5
6
  import { createRequire } from "node:module";
6
7
  import path from "node:path";
7
8
  import { afterAll, expect, vi } from "vitest";
@@ -215,78 +216,23 @@ function createModalMock() {
215
216
  return Modal;
216
217
  }
217
218
  //#endregion
218
- //#region src/mocks/components/Pressable.ts
219
- function createPressableMock() {
220
- const Pressable = React.forwardRef((props, ref) => {
221
- const { disabled, accessibilityState, ...rest } = props;
222
- const mergedA11yState = disabled || accessibilityState ? {
223
- ...accessibilityState,
224
- ...disabled ? { disabled: true } : {}
225
- } : void 0;
226
- return React.createElement("Pressable", {
227
- accessible: true,
228
- ...rest,
229
- ...mergedA11yState ? { accessibilityState: mergedA11yState } : {},
230
- ref
231
- });
232
- });
233
- Pressable.displayName = "Pressable";
234
- return Pressable;
235
- }
236
- //#endregion
237
219
  //#region src/mocks/components/TouchableOpacity.ts
238
220
  function createTouchableOpacityMock() {
239
- const TouchableOpacity = React.forwardRef((props, ref) => {
240
- const { disabled, accessibilityState, ...rest } = props;
241
- const mergedA11yState = disabled || accessibilityState ? {
242
- ...accessibilityState,
243
- ...disabled ? { disabled: true } : {}
244
- } : void 0;
245
- return React.createElement("TouchableOpacity", {
246
- accessible: true,
247
- ...rest,
248
- ...mergedA11yState ? { accessibilityState: mergedA11yState } : {},
249
- ref
250
- });
251
- });
221
+ const TouchableOpacity = React.forwardRef((props, ref) => React.createElement("TouchableOpacity", buildPressableHostProps(props, ref)));
252
222
  TouchableOpacity.displayName = "TouchableOpacity";
253
223
  return TouchableOpacity;
254
224
  }
255
225
  //#endregion
256
226
  //#region src/mocks/components/TouchableHighlight.ts
257
227
  function createTouchableHighlightMock() {
258
- const TouchableHighlight = React.forwardRef((props, ref) => {
259
- const { disabled, accessibilityState, ...rest } = props;
260
- const mergedA11yState = disabled || accessibilityState ? {
261
- ...accessibilityState,
262
- ...disabled ? { disabled: true } : {}
263
- } : void 0;
264
- return React.createElement("TouchableHighlight", {
265
- accessible: true,
266
- ...rest,
267
- ...mergedA11yState ? { accessibilityState: mergedA11yState } : {},
268
- ref
269
- });
270
- });
228
+ const TouchableHighlight = React.forwardRef((props, ref) => React.createElement("TouchableHighlight", buildPressableHostProps(props, ref)));
271
229
  TouchableHighlight.displayName = "TouchableHighlight";
272
230
  return TouchableHighlight;
273
231
  }
274
232
  //#endregion
275
233
  //#region src/mocks/components/TouchableWithoutFeedback.ts
276
234
  function createTouchableWithoutFeedbackMock() {
277
- const TouchableWithoutFeedback = React.forwardRef((props, ref) => {
278
- const { disabled, accessibilityState, ...rest } = props;
279
- const mergedA11yState = disabled || accessibilityState ? {
280
- ...accessibilityState,
281
- ...disabled ? { disabled: true } : {}
282
- } : void 0;
283
- return React.createElement("TouchableWithoutFeedback", {
284
- accessible: true,
285
- ...rest,
286
- ...mergedA11yState ? { accessibilityState: mergedA11yState } : {},
287
- ref
288
- });
289
- });
235
+ const TouchableWithoutFeedback = React.forwardRef((props, ref) => React.createElement("TouchableWithoutFeedback", buildPressableHostProps(props, ref)));
290
236
  TouchableWithoutFeedback.displayName = "TouchableWithoutFeedback";
291
237
  return TouchableWithoutFeedback;
292
238
  }
@@ -299,6 +245,12 @@ function createTouchableNativeFeedbackMock() {
299
245
  ...accessibilityState,
300
246
  ...disabled ? { disabled: true } : {}
301
247
  } : void 0;
248
+ if (disabled) {
249
+ delete rest.onPress;
250
+ delete rest.onPressIn;
251
+ delete rest.onPressOut;
252
+ delete rest.onLongPress;
253
+ }
302
254
  return React.createElement("TouchableNativeFeedback", {
303
255
  accessible: true,
304
256
  ...rest,
@@ -325,20 +277,16 @@ function createActivityIndicatorMock() {
325
277
  //#region src/mocks/components/Button.ts
326
278
  function createButtonMock() {
327
279
  function Button(props) {
328
- const { title, onPress, disabled, color, accessibilityLabel, accessibilityState, testID, ...rest } = props;
329
- return React.createElement("View", {
280
+ const { title, onPress, disabled, color, accessibilityLabel, accessibilityState, ...rest } = props;
281
+ const hostProps = buildPressableHostProps({
330
282
  ...rest,
331
- testID,
332
- onPress: disabled ? void 0 : onPress,
283
+ onPress,
284
+ disabled,
285
+ accessibilityState,
333
286
  accessibilityLabel: accessibilityLabel || title,
334
- accessibilityRole: "button",
335
- accessibilityState: disabled ? {
336
- ...accessibilityState,
337
- disabled: true
338
- } : accessibilityState,
339
- accessible: true,
340
- disabled
341
- }, React.createElement("Text", {
287
+ accessibilityRole: "button"
288
+ }, void 0);
289
+ return React.createElement("View", hostProps, React.createElement("Text", {
342
290
  style: color ? { color } : void 0,
343
291
  disabled
344
292
  }, title));
@@ -351,6 +299,7 @@ function createButtonMock() {
351
299
  function createSwitchMock() {
352
300
  const Switch = React.forwardRef((props, ref) => {
353
301
  return React.createElement("RCTSwitch", {
302
+ accessibilityRole: "switch",
354
303
  ...props,
355
304
  ref
356
305
  });
@@ -578,8 +527,8 @@ function flattenImpl(style) {
578
527
  }
579
528
  return hasAny ? result : void 0;
580
529
  }
581
- function createStyleSheetMock() {
582
- return {
530
+ function createStyleSheetMock(getScale = () => 3) {
531
+ const sheet = {
583
532
  create: vi.fn((styles) => {
584
533
  return styles;
585
534
  }),
@@ -599,50 +548,228 @@ function createStyleSheetMock() {
599
548
  top: 0,
600
549
  bottom: 0
601
550
  },
602
- hairlineWidth: .5,
603
551
  setStyleAttributePreprocessor: vi.fn()
604
552
  };
553
+ Object.defineProperty(sheet, "hairlineWidth", {
554
+ enumerable: true,
555
+ configurable: true,
556
+ get() {
557
+ const ratio = getScale();
558
+ const width = Math.round(.4 * ratio) / ratio;
559
+ return width === 0 ? 1 / ratio : width;
560
+ }
561
+ });
562
+ return sheet;
605
563
  }
606
564
  //#endregion
607
565
  //#region src/mocks/apis/Animated.ts
608
- function toNum(v) {
609
- return typeof v === "number" ? v : parseFloat(v) || 0;
566
+ const IDENTITY_EASING = (t) => t;
567
+ function interpolateSegment(input, inputMin, inputMax, outputMin, outputMax, easing, extrapolateLeft, extrapolateRight) {
568
+ let result = input;
569
+ if (result < inputMin) {
570
+ if (extrapolateLeft === "identity") return result;
571
+ else if (extrapolateLeft === "clamp") result = inputMin;
572
+ }
573
+ if (result > inputMax) {
574
+ if (extrapolateRight === "identity") return result;
575
+ else if (extrapolateRight === "clamp") result = inputMax;
576
+ }
577
+ if (outputMin === outputMax) return outputMin;
578
+ if (inputMin === inputMax) return input <= inputMin ? outputMin : outputMax;
579
+ if (inputMin === -Infinity) result = -result;
580
+ else if (inputMax === Infinity) result = result - inputMin;
581
+ else result = (result - inputMin) / (inputMax - inputMin);
582
+ result = easing(result);
583
+ if (outputMin === -Infinity) result = -result;
584
+ else if (outputMax === Infinity) result = result + outputMin;
585
+ else result = result * (outputMax - outputMin) + outputMin;
586
+ return result;
610
587
  }
611
- function interpolateValue(value, inputRange, outputRange, extrapolate, extrapolateLeft, extrapolateRight, easing) {
612
- let i = 0;
613
- for (; i < inputRange.length - 2; i++) if (value <= inputRange[i + 1]) break;
614
- const inMin = inputRange[i];
615
- const inMax = inputRange[i + 1];
616
- const outMin = toNum(outputRange[i]);
617
- const outMax = toNum(outputRange[i + 1]);
618
- if (inMax === inMin) {
619
- const result = value <= inMin ? outMin : outMax;
620
- if (value < inputRange[0]) {
621
- const leftMode = extrapolateLeft || extrapolate;
622
- if (leftMode === "clamp") return toNum(outputRange[0]);
623
- if (leftMode === "identity") return value;
624
- }
625
- if (value > inputRange[inputRange.length - 1]) {
626
- const rightMode = extrapolateRight || extrapolate;
627
- if (rightMode === "clamp") return toNum(outputRange[outputRange.length - 1]);
628
- if (rightMode === "identity") return value;
629
- }
630
- return result;
588
+ function findRangeIndex(input, inputRange) {
589
+ let i;
590
+ for (i = 1; i < inputRange.length - 1; ++i) if (inputRange[i] >= input) break;
591
+ return i - 1;
592
+ }
593
+ function interpolateNumeric(value, inputRange, outputRange, extrapolate, extrapolateLeft, extrapolateRight, easing) {
594
+ const i = findRangeIndex(value, inputRange);
595
+ return interpolateSegment(value, inputRange[i], inputRange[i + 1], outputRange[i], outputRange[i + 1], easing, extrapolateLeft ?? extrapolate, extrapolateRight ?? extrapolate);
596
+ }
597
+ const NAMED_COLORS = {
598
+ red: [
599
+ 255,
600
+ 0,
601
+ 0,
602
+ 1
603
+ ],
604
+ green: [
605
+ 0,
606
+ 128,
607
+ 0,
608
+ 1
609
+ ],
610
+ blue: [
611
+ 0,
612
+ 0,
613
+ 255,
614
+ 1
615
+ ],
616
+ white: [
617
+ 255,
618
+ 255,
619
+ 255,
620
+ 1
621
+ ],
622
+ black: [
623
+ 0,
624
+ 0,
625
+ 0,
626
+ 1
627
+ ],
628
+ transparent: [
629
+ 0,
630
+ 0,
631
+ 0,
632
+ 0
633
+ ],
634
+ yellow: [
635
+ 255,
636
+ 255,
637
+ 0,
638
+ 1
639
+ ],
640
+ cyan: [
641
+ 0,
642
+ 255,
643
+ 255,
644
+ 1
645
+ ],
646
+ magenta: [
647
+ 255,
648
+ 0,
649
+ 255,
650
+ 1
651
+ ],
652
+ orange: [
653
+ 255,
654
+ 165,
655
+ 0,
656
+ 1
657
+ ],
658
+ purple: [
659
+ 128,
660
+ 0,
661
+ 128,
662
+ 1
663
+ ],
664
+ gray: [
665
+ 128,
666
+ 128,
667
+ 128,
668
+ 1
669
+ ],
670
+ grey: [
671
+ 128,
672
+ 128,
673
+ 128,
674
+ 1
675
+ ]
676
+ };
677
+ function colorToRgba(input) {
678
+ const s = input.toLowerCase().trim();
679
+ if (NAMED_COLORS[s]) return [...NAMED_COLORS[s]];
680
+ let m;
681
+ if (m = s.match(/^#([0-9a-f]{3})$/)) {
682
+ const [r, g, b] = m[1].split("");
683
+ return [
684
+ parseInt(r + r, 16),
685
+ parseInt(g + g, 16),
686
+ parseInt(b + b, 16),
687
+ 1
688
+ ];
631
689
  }
632
- let t = (value - inMin) / (inMax - inMin);
633
- if (easing) t = easing(t);
634
- let result = outMin + t * (outMax - outMin);
635
- const leftMode = extrapolateLeft || extrapolate;
636
- const rightMode = extrapolateRight || extrapolate;
637
- if (value < inputRange[0]) {
638
- if (leftMode === "clamp") return toNum(outputRange[0]);
639
- if (leftMode === "identity") return value;
690
+ if (m = s.match(/^#([0-9a-f]{6})$/)) {
691
+ const n = m[1];
692
+ return [
693
+ parseInt(n.slice(0, 2), 16),
694
+ parseInt(n.slice(2, 4), 16),
695
+ parseInt(n.slice(4, 6), 16),
696
+ 1
697
+ ];
640
698
  }
641
- if (value > inputRange[inputRange.length - 1]) {
642
- if (rightMode === "clamp") return toNum(outputRange[outputRange.length - 1]);
643
- if (rightMode === "identity") return value;
699
+ if (m = s.match(/^#([0-9a-f]{8})$/)) {
700
+ const n = m[1];
701
+ return [
702
+ parseInt(n.slice(0, 2), 16),
703
+ parseInt(n.slice(2, 4), 16),
704
+ parseInt(n.slice(4, 6), 16),
705
+ parseInt(n.slice(6, 8), 16) / 255
706
+ ];
644
707
  }
645
- return result;
708
+ if (m = s.match(/^rgb\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/)) return [
709
+ +m[1],
710
+ +m[2],
711
+ +m[3],
712
+ 1
713
+ ];
714
+ if (m = s.match(/^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/)) return [
715
+ +m[1],
716
+ +m[2],
717
+ +m[3],
718
+ +m[4]
719
+ ];
720
+ return null;
721
+ }
722
+ const NUMERIC_COMPONENT_RE = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g;
723
+ function mapStringToComponents(input) {
724
+ const rgba = colorToRgba(input);
725
+ if (rgba) return {
726
+ isColor: true,
727
+ components: rgba
728
+ };
729
+ const components = [];
730
+ let lastMatchEnd = 0;
731
+ let match;
732
+ NUMERIC_COMPONENT_RE.lastIndex = 0;
733
+ while ((match = NUMERIC_COMPONENT_RE.exec(input)) != null) {
734
+ if (match.index > lastMatchEnd) components.push(input.substring(lastMatchEnd, match.index));
735
+ components.push(parseFloat(match[0]));
736
+ lastMatchEnd = match.index + match[0].length;
737
+ }
738
+ if (components.length === 0) throw new Error("outputRange must contain color or value with numeric component");
739
+ if (lastMatchEnd < input.length) components.push(input.substring(lastMatchEnd, input.length));
740
+ return {
741
+ isColor: false,
742
+ components
743
+ };
744
+ }
745
+ function prepareStringInterpolation(outputRange) {
746
+ const mapped = outputRange.map(mapStringToComponents);
747
+ const isColor = mapped[0].isColor;
748
+ if (!mapped.every((o) => o.isColor === isColor)) throw new Error("All elements of output range should either be a color or a string with numeric components");
749
+ const first = mapped[0].components;
750
+ if (!mapped.every((o) => o.components.length === first.length)) throw new Error("All elements of output range should have the same number of components");
751
+ if (!mapped.every((o) => o.components.every((c, i) => typeof c === "number" || c === first[i]))) throw new Error("All elements of output range should have the same non-numeric components");
752
+ const numericComponents = mapped.map((o) => isColor ? o.components : o.components.filter((c) => typeof c === "number"));
753
+ return {
754
+ isColor,
755
+ template: first,
756
+ perSlotRanges: numericComponents[0].map((_, i) => numericComponents.map((c) => c[i]))
757
+ };
758
+ }
759
+ function interpolateString(prepared, value, inputRange, extrapolate, extrapolateLeft, extrapolateRight, easing) {
760
+ const slots = prepared.perSlotRanges.map((range) => interpolateNumeric(value, inputRange, range, extrapolate, extrapolateLeft, extrapolateRight, easing));
761
+ if (prepared.isColor) {
762
+ const r = slots.map((v, i) => i < 3 ? Math.round(v) : Math.round(v * 1e3) / 1e3);
763
+ return `rgba(${r[0]}, ${r[1]}, ${r[2]}, ${r[3]})`;
764
+ }
765
+ let i = 0;
766
+ return prepared.template.map((c) => typeof c === "number" ? slots[i++] : c).join("");
767
+ }
768
+ function checkValidRanges(inputRange, outputRange) {
769
+ if (inputRange.length === 2 && inputRange[0] === -Infinity && inputRange[1] === Infinity) throw new Error("inputRange cannot be [-Infinity, Infinity]");
770
+ if (inputRange.length < 2) throw new Error("inputRange must have at least 2 elements");
771
+ for (let i = 1; i < inputRange.length; ++i) if (!(inputRange[i] >= inputRange[i - 1])) throw new Error("inputRange must be monotonically non-decreasing " + String(inputRange));
772
+ if (inputRange.length !== outputRange.length) throw new Error("inputRange (" + inputRange.length + ") and outputRange (" + outputRange.length + ") must have the same length");
646
773
  }
647
774
  var AnimatedValue = class AnimatedValue {
648
775
  _value;
@@ -671,9 +798,27 @@ var AnimatedValue = class AnimatedValue {
671
798
  this._listeners.clear();
672
799
  }
673
800
  interpolate(config) {
674
- const { inputRange, outputRange, extrapolate = "extend", extrapolateLeft, extrapolateRight, easing } = config || {};
801
+ const { inputRange, outputRange, extrapolate = "extend", extrapolateLeft, extrapolateRight, easing = IDENTITY_EASING } = config || {};
675
802
  if (!inputRange || !outputRange || inputRange.length < 2 || outputRange.length < 2) return new AnimatedValue(this._value);
676
- return new AnimatedValue(interpolateValue(this._value, inputRange, outputRange, extrapolate, extrapolateLeft, extrapolateRight, easing));
803
+ checkValidRanges(inputRange, outputRange);
804
+ if (typeof outputRange[0] === "string") {
805
+ const prepared = prepareStringInterpolation(outputRange);
806
+ const compute = () => interpolateString(prepared, this._value, inputRange, extrapolate, extrapolateLeft, extrapolateRight, easing);
807
+ return {
808
+ getValue: compute,
809
+ __getValue: compute,
810
+ toJSON: compute,
811
+ interpolate: () => {
812
+ throw new Error("Cannot chain an interpolation off a string-valued interpolation");
813
+ },
814
+ addListener: () => "0",
815
+ removeListener: () => {},
816
+ removeAllListeners: () => {},
817
+ stopAnimation: (cb) => cb?.(compute()),
818
+ resetAnimation: (cb) => cb?.(compute())
819
+ };
820
+ }
821
+ return new AnimatedValue(interpolateNumeric(this._value, inputRange, outputRange, extrapolate, extrapolateLeft, extrapolateRight, easing));
677
822
  }
678
823
  stopAnimation(callback) {
679
824
  callback?.(this._value);
@@ -2162,7 +2307,7 @@ function buildReactNativeMock(platform = "ios") {
2162
2307
  DrawerLayoutAndroid: createDrawerLayoutAndroidMock(),
2163
2308
  Platform: createPlatformMock(platform),
2164
2309
  Dimensions: createDimensionsMock(),
2165
- StyleSheet: createStyleSheetMock(),
2310
+ StyleSheet: createStyleSheetMock(() => mock.Dimensions.get("window").scale),
2166
2311
  Animated: createAnimatedMock(),
2167
2312
  Alert: createAlertMock(),
2168
2313
  Linking: createLinkingMock(),
@@ -2495,6 +2640,8 @@ try {
2495
2640
  } catch (e) {
2496
2641
  if (diagnostics) console.log(`[vitest-native] Could not load RNTL matchers: ${e?.message}`);
2497
2642
  }
2643
+ expect.extend(animatedMatchers);
2644
+ if (diagnostics) console.log(`[vitest-native] Registered ${Object.keys(animatedMatchers).length} animated matchers: ${Object.keys(animatedMatchers).join(", ")}`);
2498
2645
  expect.addSnapshotSerializer(serializer);
2499
2646
  afterAll(() => {
2500
2647
  uninstallCjsBridge();
@@ -0,0 +1,123 @@
1
+ # Migrating an existing Jest suite to vitest-native
2
+
3
+ **Honest expectation first:** this is **not a turnkey drop-in.** Real React Native Jest suites
4
+ couple to Jest at several levels (the `jest` global, `@jest/globals`, `jest.mock('react-native')`,
5
+ `@react-native/jest-preset`, jest-native matchers, recorded snapshots). The `vitest-native/jest-compat`
6
+ layer clears the *API coupling* mechanically; the rest is a small, well-defined per-suite cleanup.
7
+
8
+ This guide is grounded in real migration runs against production apps — **react-native-paper**
9
+ (fresh component tests), the **obytes template**, and **Rocket.Chat** (existing Jest suites).
10
+
11
+ ---
12
+
13
+ ## 1. The jest-compat layer (clears API coupling)
14
+
15
+ ```ts
16
+ // vitest.config.mts
17
+ import { defineConfig } from "vitest/config";
18
+ import { reactNative } from "vitest-native";
19
+ import { jestCompatAliases, jestCompatSetup, jestMockTransform } from "vitest-native/jest-compat";
20
+
21
+ export default defineConfig({
22
+ plugins: [reactNative({ engine: "native" }), jestMockTransform()], // or engine: "mock"
23
+ resolve: {
24
+ dedupe: ["react", "react-test-renderer", "react-is"],
25
+ alias: { ...jestCompatAliases() },
26
+ },
27
+ test: {
28
+ globals: true,
29
+ environment: "node",
30
+ setupFiles: [jestCompatSetup],
31
+ },
32
+ });
33
+ ```
34
+
35
+ What each piece does:
36
+
37
+ | Piece | Clears |
38
+ |---|---|
39
+ | `jestCompatSetup` (a setup file) | Installs a `jest` global backed by Vitest's `vi`, plus the sync `jest.requireActual` / `jest.requireMock` that Vitest only ships as the async `vi.importActual`. |
40
+ | `jestMockTransform()` (a plugin) | Rewrites top-level `jest.mock(...)` to a **hoisted** `vi.mock(...)` so it actually applies — see 2a. The single biggest mechanical blocker, automated. |
41
+ | `jestCompatAliases()` → `@jest/globals` | Redirects `@jest/globals` (imported by **@testing-library/react-native < 12**) to a shim re-exporting Vitest's globals. |
42
+ | `jestCompatAliases()` → `@testing-library/jest-native/extend-expect` | No-ops it — vitest-native already registers the jest-native matchers (`toHaveStyle`, `toBeVisible`, …). |
43
+
44
+ After this, `jest.fn`, `jest.spyOn`, `jest.useFakeTimers`, `jest.requireActual`, and top-level
45
+ `jest.mock` / `jest.unmock` / `jest.doMock` calls all work unchanged.
46
+
47
+ ---
48
+
49
+ ## 2. Per-suite cleanup still required
50
+
51
+ These are the things the compat layer **cannot** do for you. Each is small and mechanical.
52
+
53
+ ### 2a. Top-level `jest.mock(...)` — automated by `jestMockTransform()`
54
+ Vitest only **hoists** mock calls made on the `vi` / `vitest` identifier. A top-level
55
+ `jest.mock('react-native', factory)` would otherwise run *after* imports and silently not apply.
56
+
57
+ **`jestMockTransform()` (section 1) handles this for you** — it rewrites top-level
58
+ `jest.mock` / `jest.unmock` / `jest.doMock` / `jest.doUnmock` to the hoisted `vi.*` form, and
59
+ runs each `mock`/`doMock` factory's return through **Jest's CommonJS interop** so the two most
60
+ common Jest manual-mock shapes resolve the way they do under Jest:
61
+
62
+ ```ts
63
+ jest.mock('./Icon', () => () => null); // function factory → usable as `import Icon from`
64
+ jest.mock('./api', () => ({ get: vi.fn() })); // named-only → `import api from` gets the object
65
+ ```
66
+
67
+ (Jest treats a factory return as `module.exports`; Vitest treats it as an ES namespace. The
68
+ wrapper bridges that. A factory already returning an ES shape — `__esModule` or an explicit
69
+ `default` — is left as-is.) So you can leave existing `jest.mock(...)` calls unchanged. It keys
70
+ on the literal `jest.mock` member form, not `jest` aliased to another local name.
71
+
72
+ …and in most cases you can **delete** third-party native-lib mocks entirely — see 2c.
73
+
74
+ ### 2b. Upgrade RNTL to ≥ 12 (recommended)
75
+ The `@jest/globals` alias unblocks RNTL < 12, but **upgrading to `@testing-library/react-native@^12`
76
+ is the cleaner fix** (12 dropped the `@jest/globals` dependency). vitest-native targets RNTL ≥ 12.
77
+
78
+ ### 2c. Delete third-party native-lib mocks — they're automatic now
79
+ You do **not** need `jest.mock('react-native-reanimated', …)`, safe-area's `jest/mock`,
80
+ gesture-handler's jestSetup, etc. vitest-native **auto-detects** installed third-party libraries and
81
+ shadows their native runtimes with built-in presets, under **both** engines. Just have the package
82
+ installed; delete the manual mock. (Reanimated, Gesture Handler, Safe Area, Navigation, Screens,
83
+ AsyncStorage, Expo are covered out of the box. Validated under the native engine —
84
+ `tests-native/third-party-stack.test.tsx`.)
85
+
86
+ ### 2d. Re-record snapshots (`vitest -u`)
87
+ This is the most common surprise. Under `engine: 'native'`, real React Native renders **real host
88
+ component names** (`RCTText`, `RCTView`, `RCTScrollView`), whereas `@react-native/jest-preset`
89
+ snapshots show mock names (`Text`, `View`). Existing snapshots will mismatch on names only. Run once
90
+ with `-u` to re-record; the rendered structure is otherwise equivalent. (In the Paper run, every
91
+ own-test passed after a single `-u`.)
92
+
93
+ > Tip: prefer explicit queries (`getByText`, `getByTestId`, `getByRole`) over large snapshots —
94
+ > they're robust across the engine's real host names and far easier to review.
95
+
96
+ ### 2e. Drop `@react-native/jest-preset` and `transform`/`transformIgnorePatterns`
97
+ Those are Jest/Metro config. vitest-native handles RN + third-party transformation itself
98
+ (`engine: 'native'` transforms real RN in Node's loader hooks; the mock engine virtualizes RN).
99
+ For *run-real pure-JS* third-party libs under the native engine, use the plugin's `transform: [...]`
100
+ allowlist instead of `transformIgnorePatterns`.
101
+
102
+ ### 2f. Jest config options
103
+ `jest.config.js` keys (`setupFilesAfterEnv`, `moduleNameMapper`, `testEnvironment`, etc.) move to the
104
+ Vitest config: `setupFiles`, `resolve.alias`, `test.environment: 'node'`. `jest.setTimeout(ms)` is a
105
+ no-op under the shim (use `test.testTimeout` in config or per-test `{ timeout }`).
106
+
107
+ ---
108
+
109
+ ## 3. Suggested migration recipe
110
+
111
+ 1. Add the jest-compat config (section 1). Upgrade RNTL to ≥ 12 (2b).
112
+ 2. Delete manual third-party native-lib mocks and `@react-native/jest-preset` (2c, 2e).
113
+ 3. Convert any **top-level** `jest.mock(...)` to `vi.mock(...)`; leave runtime `jest.*` as-is (2a).
114
+ 4. Run `vitest run -u` once to re-record snapshots (2d), then `vitest run` to confirm green.
115
+ 5. Triage remaining failures — usually a missing query update or a suite-specific mock.
116
+
117
+ ## 4. What "done" looks like
118
+
119
+ A migrated suite runs under Vitest with: the jest-compat aliases + setup, RNTL ≥ 12, no manual
120
+ third-party native mocks, top-level mocks converted, and snapshots re-recorded. You get Vitest's
121
+ speed/watch/UI while keeping `engine: 'native'` real-RN fidelity (or `engine: 'mock'` for the fast
122
+ path). The compat layer is intentionally small — it removes the mechanical Jest coupling so the only
123
+ work left is the genuinely suite-specific bits.