@testing-library/react-native 12.1.1 → 12.1.3

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 (372) hide show
  1. package/.DS_Store +0 -0
  2. package/.codecov.yml +9 -0
  3. package/.eslintcache +1 -0
  4. package/.eslintignore +2 -0
  5. package/.eslintrc +19 -0
  6. package/.flowconfig +63 -0
  7. package/.github/ISSUE_TEMPLATE/bug_report.md +38 -0
  8. package/.github/ISSUE_TEMPLATE/feature_request.md +14 -0
  9. package/.github/ISSUE_TEMPLATE/question.md +9 -0
  10. package/.github/PULL_REQUEST_TEMPLATE.md +10 -0
  11. package/.github/actions/setup-deps/action.yml +22 -0
  12. package/.github/actions/setup-website-deps/action.yml +22 -0
  13. package/.github/dependabot.yml +10 -0
  14. package/.github/workflows/deploy-website.yml +36 -0
  15. package/.github/workflows/example-apps.yml +25 -0
  16. package/.github/workflows/main.yml +103 -0
  17. package/.gitignore +11 -0
  18. package/.prettierrc.js +5 -0
  19. package/CODE_OF_CONDUCT.md +73 -0
  20. package/CONTRIBUTING.md +64 -0
  21. package/README.md +8 -7
  22. package/babel.config.js +22 -0
  23. package/build/act.js.map +1 -1
  24. package/build/cleanup.js.map +1 -1
  25. package/build/config.d.ts +1 -0
  26. package/build/config.js.map +1 -1
  27. package/build/fireEvent.d.ts +13 -5
  28. package/build/fireEvent.js +57 -48
  29. package/build/fireEvent.js.map +1 -1
  30. package/build/flush-micro-tasks.d.ts +19 -0
  31. package/build/flush-micro-tasks.js +36 -0
  32. package/build/flush-micro-tasks.js.map +1 -0
  33. package/build/helpers/accessiblity.js +3 -1
  34. package/build/helpers/accessiblity.js.map +1 -1
  35. package/build/helpers/component-tree.d.ts +0 -15
  36. package/build/helpers/component-tree.js +0 -45
  37. package/build/helpers/component-tree.js.map +1 -1
  38. package/build/helpers/deprecation.d.ts +1 -0
  39. package/build/helpers/deprecation.js +16 -0
  40. package/build/helpers/deprecation.js.map +1 -1
  41. package/build/helpers/errors.d.ts +0 -4
  42. package/build/helpers/errors.js +1 -25
  43. package/build/helpers/errors.js.map +1 -1
  44. package/build/helpers/findAll.js.map +1 -1
  45. package/build/helpers/format-default.js.map +1 -1
  46. package/build/helpers/format.js.map +1 -1
  47. package/build/helpers/host-component-names.js +4 -1
  48. package/build/helpers/host-component-names.js.map +1 -1
  49. package/build/helpers/matchers/matchLabelText.js.map +1 -1
  50. package/build/helpers/pointer-events.d.ts +9 -0
  51. package/build/helpers/pointer-events.js +25 -0
  52. package/build/helpers/pointer-events.js.map +1 -0
  53. package/build/helpers/stringValidation.js.map +1 -1
  54. package/build/helpers/timers.js.map +1 -1
  55. package/build/index.js +2 -2
  56. package/build/index.js.map +1 -1
  57. package/build/matches.js.map +1 -1
  58. package/build/pure.d.ts +1 -1
  59. package/build/pure.js.map +1 -1
  60. package/build/queries/a11yState.js.map +1 -1
  61. package/build/queries/a11yValue.js.map +1 -1
  62. package/build/queries/displayValue.js.map +1 -1
  63. package/build/queries/hintText.js.map +1 -1
  64. package/build/queries/labelText.js.map +1 -1
  65. package/build/queries/makeQueries.js.map +1 -1
  66. package/build/queries/placeholderText.js.map +1 -1
  67. package/build/queries/role.js.map +1 -1
  68. package/build/queries/testId.js.map +1 -1
  69. package/build/queries/text.js.map +1 -1
  70. package/build/queries/unsafeProps.js.map +1 -1
  71. package/build/render.d.ts +171 -12
  72. package/build/render.js +11 -4
  73. package/build/render.js.map +1 -1
  74. package/build/renderHook.d.ts +3 -6
  75. package/build/renderHook.js +4 -3
  76. package/build/renderHook.js.map +1 -1
  77. package/build/shallow.js.map +1 -1
  78. package/build/test-utils/events.d.ts +10 -0
  79. package/build/test-utils/events.js +27 -0
  80. package/build/test-utils/events.js.map +1 -0
  81. package/build/test-utils/index.d.ts +1 -0
  82. package/build/test-utils/index.js +17 -0
  83. package/build/test-utils/index.js.map +1 -0
  84. package/build/user-event/event-builder/common.d.ts +45 -0
  85. package/build/user-event/event-builder/common.js +58 -0
  86. package/build/user-event/event-builder/common.js.map +1 -0
  87. package/build/user-event/event-builder/index.d.ts +32 -0
  88. package/build/user-event/event-builder/index.js +12 -0
  89. package/build/user-event/event-builder/index.js.map +1 -0
  90. package/build/user-event/index.d.ts +9 -0
  91. package/build/user-event/index.js +16 -0
  92. package/build/user-event/index.js.map +1 -0
  93. package/build/user-event/press/constants.d.ts +2 -0
  94. package/build/user-event/press/constants.js +16 -0
  95. package/build/user-event/press/constants.js.map +1 -0
  96. package/build/user-event/press/index.d.ts +1 -0
  97. package/build/user-event/press/index.js +19 -0
  98. package/build/user-event/press/index.js.map +1 -0
  99. package/build/user-event/press/press.d.ts +7 -0
  100. package/build/user-event/press/press.js +106 -0
  101. package/build/user-event/press/press.js.map +1 -0
  102. package/build/user-event/press/utils/warnAboutRealTimers.d.ts +1 -0
  103. package/build/user-event/press/utils/warnAboutRealTimers.js +14 -0
  104. package/build/user-event/press/utils/warnAboutRealTimers.js.map +1 -0
  105. package/build/user-event/setup/index.d.ts +2 -0
  106. package/build/user-event/setup/index.js +13 -0
  107. package/build/user-event/setup/index.js.map +1 -0
  108. package/build/user-event/setup/setup.d.ts +39 -0
  109. package/build/user-event/setup/setup.js +56 -0
  110. package/build/user-event/setup/setup.js.map +1 -0
  111. package/build/user-event/type/index.d.ts +1 -0
  112. package/build/user-event/type/index.js +13 -0
  113. package/build/user-event/type/index.js.map +1 -0
  114. package/build/user-event/type/type.d.ts +3 -0
  115. package/build/user-event/type/type.js +18 -0
  116. package/build/user-event/type/type.js.map +1 -0
  117. package/build/user-event/utils/events.d.ts +9 -0
  118. package/build/user-event/utils/events.js +44 -0
  119. package/build/user-event/utils/events.js.map +1 -0
  120. package/build/user-event/utils/index.d.ts +2 -0
  121. package/build/user-event/utils/index.js +28 -0
  122. package/build/user-event/utils/index.js.map +1 -0
  123. package/build/user-event/utils/wait.d.ts +2 -0
  124. package/build/user-event/utils/wait.js +14 -0
  125. package/build/user-event/utils/wait.js.map +1 -0
  126. package/build/waitFor.js +3 -3
  127. package/build/waitFor.js.map +1 -1
  128. package/build/waitForElementToBeRemoved.js.map +1 -1
  129. package/examples/basic/.expo-shared/assets.json +4 -0
  130. package/examples/basic/.gitignore +14 -0
  131. package/examples/basic/App.tsx +20 -0
  132. package/examples/basic/README.md +11 -0
  133. package/examples/basic/__tests__/App.test.tsx +119 -0
  134. package/examples/basic/app.json +31 -0
  135. package/examples/basic/assets/adaptive-icon.png +0 -0
  136. package/examples/basic/assets/favicon.png +0 -0
  137. package/examples/basic/assets/icon.png +0 -0
  138. package/examples/basic/assets/splash.png +0 -0
  139. package/examples/basic/babel.config.js +6 -0
  140. package/examples/basic/components/Home.tsx +28 -0
  141. package/examples/basic/components/LoginForm.tsx +138 -0
  142. package/examples/basic/jest-setup.ts +7 -0
  143. package/examples/basic/jest.config.js +5 -0
  144. package/examples/basic/package.json +30 -0
  145. package/examples/basic/tsconfig.json +7 -0
  146. package/examples/react-navigation/README.md +14 -0
  147. package/examples/react-navigation/babel.config.js +4 -0
  148. package/examples/react-navigation/jest-setup.js +11 -0
  149. package/examples/react-navigation/jest.config.js +10 -0
  150. package/examples/react-navigation/package.json +31 -0
  151. package/examples/react-navigation/src/App.js +21 -0
  152. package/examples/react-navigation/src/DrawerNavigator.js +15 -0
  153. package/examples/react-navigation/src/DrawerNavigator.test.js +42 -0
  154. package/examples/react-navigation/src/NativeStackNavigator.js +15 -0
  155. package/examples/react-navigation/src/NativeStackNavigator.test.js +34 -0
  156. package/examples/react-navigation/src/StackNavigator.js +15 -0
  157. package/examples/react-navigation/src/StackNavigator.test.js +34 -0
  158. package/examples/react-navigation/src/TabNavigator.js +15 -0
  159. package/examples/react-navigation/src/TabNavigator.test.js +21 -0
  160. package/examples/react-navigation/src/screens/DetailsScreen.js +43 -0
  161. package/examples/react-navigation/src/screens/DetailsScreen.test.js +27 -0
  162. package/examples/react-navigation/src/screens/DrawerHomeScreen.js +26 -0
  163. package/examples/react-navigation/src/screens/HomeScreen.js +48 -0
  164. package/examples/react-navigation/src/screens/SettingsScreen.js +20 -0
  165. package/examples/react-navigation/src/test-utils.js +12 -0
  166. package/examples/redux/App.js +27 -0
  167. package/examples/redux/actions/todoActions.js +25 -0
  168. package/examples/redux/babel.config.js +6 -0
  169. package/examples/redux/components/AddTodo.js +73 -0
  170. package/examples/redux/components/AddTodo.test.js +27 -0
  171. package/examples/redux/components/TodoElem.js +25 -0
  172. package/examples/redux/components/TodoList.js +29 -0
  173. package/examples/redux/components/TodoList.test.js +34 -0
  174. package/examples/redux/index.js +8 -0
  175. package/examples/redux/jest-setup.js +2 -0
  176. package/examples/redux/jest.config.js +4 -0
  177. package/examples/redux/package.json +23 -0
  178. package/examples/redux/reducers/index.js +6 -0
  179. package/examples/redux/reducers/todoReducer.js +27 -0
  180. package/examples/redux/store.js +10 -0
  181. package/examples/redux/test-utils.js +11 -0
  182. package/experiments-app/.expo/README.md +15 -0
  183. package/experiments-app/.expo/devices.json +3 -0
  184. package/experiments-app/.expo/packager-info.json +9 -0
  185. package/experiments-app/.expo/settings.json +9 -0
  186. package/experiments-app/.gitignore +17 -0
  187. package/experiments-app/.prettierrc.js +5 -0
  188. package/experiments-app/app.json +30 -0
  189. package/experiments-app/assets/adaptive-icon.png +0 -0
  190. package/experiments-app/assets/favicon.png +0 -0
  191. package/experiments-app/assets/icon.png +0 -0
  192. package/experiments-app/assets/splash.png +0 -0
  193. package/experiments-app/babel.config.js +6 -0
  194. package/experiments-app/index.js +4 -0
  195. package/experiments-app/package.json +31 -0
  196. package/experiments-app/src/App.tsx +31 -0
  197. package/experiments-app/src/MainScreen.tsx +51 -0
  198. package/experiments-app/src/experiments.ts +17 -0
  199. package/experiments-app/src/screens/TextInputEventPropagation.tsx +54 -0
  200. package/experiments-app/src/screens/TextInputEvents.tsx +50 -0
  201. package/experiments-app/src/utils/helpers.ts +8 -0
  202. package/experiments-app/tsconfig.json +6 -0
  203. package/experiments-app/yarn.lock +6913 -0
  204. package/flow-typed/npm/jest_v26.x.x.js +1218 -0
  205. package/flow-typed/npm/react-test-renderer_v16.x.x.js +81 -0
  206. package/jest-setup.ts +10 -0
  207. package/package.json +6 -6
  208. package/renovate.json +19 -0
  209. package/scripts/test_react_17 +12 -0
  210. package/src/__tests__/__snapshots__/render-debug.test.tsx.snap +548 -0
  211. package/src/__tests__/__snapshots__/render.test.tsx.snap +39 -0
  212. package/src/__tests__/act.test.tsx +52 -0
  213. package/src/__tests__/auto-cleanup-skip.test.tsx +39 -0
  214. package/src/__tests__/auto-cleanup.test.tsx +50 -0
  215. package/src/__tests__/cleanup.test.tsx +26 -0
  216. package/src/__tests__/config.test.ts +55 -0
  217. package/src/__tests__/fireEvent-textInput.test.tsx +154 -0
  218. package/src/__tests__/fireEvent.test.tsx +485 -0
  219. package/src/__tests__/host-component-names.test.tsx +109 -0
  220. package/src/__tests__/host-text-nesting.test.tsx +90 -0
  221. package/src/__tests__/jest-native.test.tsx +84 -0
  222. package/src/__tests__/questionsBoard.test.tsx +62 -0
  223. package/src/__tests__/react-native-api.test.tsx +126 -0
  224. package/src/__tests__/render-debug.test.tsx +207 -0
  225. package/src/__tests__/render-stringValidation.test.tsx +157 -0
  226. package/src/__tests__/render.test.tsx +256 -0
  227. package/src/__tests__/renderHook.test.tsx +114 -0
  228. package/src/__tests__/screen.test.tsx +66 -0
  229. package/src/__tests__/timerUtils.ts +7 -0
  230. package/src/__tests__/timers.test.ts +27 -0
  231. package/src/__tests__/waitFor.test.tsx +327 -0
  232. package/src/__tests__/waitForElementToBeRemoved.test.tsx +151 -0
  233. package/src/__tests__/within.test.tsx +96 -0
  234. package/src/act.ts +86 -0
  235. package/src/cleanup.ts +15 -0
  236. package/src/config.ts +72 -0
  237. package/src/fireEvent.ts +163 -0
  238. package/src/flush-micro-tasks.ts +30 -0
  239. package/src/helpers/__tests__/accessiblity.test.tsx +373 -0
  240. package/src/helpers/__tests__/component-tree.test.tsx +226 -0
  241. package/src/helpers/__tests__/format-default.tsx +114 -0
  242. package/src/helpers/__tests__/getTextContent.test.tsx +49 -0
  243. package/src/helpers/__tests__/includeHiddenElements.test.tsx +39 -0
  244. package/src/helpers/__tests__/query-name.test.ts +10 -0
  245. package/src/helpers/__tests__/timers.test.ts +8 -0
  246. package/src/helpers/accessiblity.ts +108 -0
  247. package/src/helpers/component-tree.ts +89 -0
  248. package/src/helpers/debugDeep.ts +27 -0
  249. package/src/helpers/debugShallow.ts +22 -0
  250. package/src/helpers/deprecation.ts +53 -0
  251. package/src/helpers/errors.ts +66 -0
  252. package/src/helpers/filterNodeByType.ts +7 -0
  253. package/src/helpers/findAll.ts +68 -0
  254. package/src/helpers/format-default.ts +72 -0
  255. package/src/helpers/format.ts +47 -0
  256. package/src/helpers/getTextContent.ts +20 -0
  257. package/src/helpers/host-component-names.tsx +67 -0
  258. package/src/helpers/matchers/__tests__/matchArrayValue.test.ts +34 -0
  259. package/src/helpers/matchers/__tests__/matchObject.test.ts +37 -0
  260. package/src/helpers/matchers/__tests__/matchStringValue.test.ts +15 -0
  261. package/src/helpers/matchers/accessibilityState.ts +48 -0
  262. package/src/helpers/matchers/accessibilityValue.ts +24 -0
  263. package/src/helpers/matchers/matchArrayProp.ts +21 -0
  264. package/src/helpers/matchers/matchLabelText.ts +51 -0
  265. package/src/helpers/matchers/matchObjectProp.ts +25 -0
  266. package/src/helpers/matchers/matchStringProp.ts +23 -0
  267. package/src/helpers/matchers/matchTextContent.ts +20 -0
  268. package/src/helpers/pointer-events.ts +27 -0
  269. package/src/helpers/query-name.ts +4 -0
  270. package/src/helpers/stringValidation.ts +36 -0
  271. package/src/helpers/timers.ts +98 -0
  272. package/src/index.ts +33 -0
  273. package/src/matches.ts +49 -0
  274. package/src/pure.ts +25 -0
  275. package/src/queries/__tests__/a11yState.test.tsx +439 -0
  276. package/src/queries/__tests__/a11yValue.test.tsx +309 -0
  277. package/src/queries/__tests__/displayValue.test.tsx +221 -0
  278. package/src/queries/__tests__/hintText.test.tsx +177 -0
  279. package/src/queries/__tests__/labelText.test.tsx +242 -0
  280. package/src/queries/__tests__/makeQueries.test.tsx +235 -0
  281. package/src/queries/__tests__/placeholderText.test.tsx +136 -0
  282. package/src/queries/__tests__/role-value.test.tsx +176 -0
  283. package/src/queries/__tests__/role.test.tsx +824 -0
  284. package/src/queries/__tests__/testId.test.tsx +200 -0
  285. package/src/queries/__tests__/text.test.tsx +556 -0
  286. package/src/queries/a11yState.ts +131 -0
  287. package/src/queries/a11yValue.ts +131 -0
  288. package/src/queries/displayValue.ts +78 -0
  289. package/src/queries/hintText.ts +112 -0
  290. package/src/queries/labelText.ts +59 -0
  291. package/src/queries/makeQueries.ts +255 -0
  292. package/src/queries/options.ts +14 -0
  293. package/src/queries/placeholderText.ts +79 -0
  294. package/src/queries/role.ts +132 -0
  295. package/src/queries/testId.ts +71 -0
  296. package/src/queries/text.ts +66 -0
  297. package/src/queries/unsafeProps.ts +76 -0
  298. package/src/queries/unsafeType.ts +73 -0
  299. package/src/react-versions.ts +11 -0
  300. package/src/render-act.ts +19 -0
  301. package/src/render.tsx +183 -0
  302. package/src/renderHook.tsx +56 -0
  303. package/src/screen.ts +123 -0
  304. package/src/shallow.ts +18 -0
  305. package/src/test-utils/events.ts +24 -0
  306. package/src/test-utils/index.ts +1 -0
  307. package/src/user-event/event-builder/common.ts +50 -0
  308. package/src/user-event/event-builder/index.ts +5 -0
  309. package/src/user-event/index.ts +14 -0
  310. package/src/user-event/press/__tests__/longPress.real-timers.test.tsx +115 -0
  311. package/src/user-event/press/__tests__/longPress.test.tsx +157 -0
  312. package/src/user-event/press/__tests__/press.real-timers.test.tsx +318 -0
  313. package/src/user-event/press/__tests__/press.test.tsx +422 -0
  314. package/src/user-event/press/constants.ts +7 -0
  315. package/src/user-event/press/index.ts +1 -0
  316. package/src/user-event/press/press.ts +134 -0
  317. package/src/user-event/press/utils/warnAboutRealTimers.ts +6 -0
  318. package/src/user-event/setup/index.ts +2 -0
  319. package/src/user-event/setup/setup.ts +93 -0
  320. package/src/user-event/type/__tests__/__snapshots__/type.test.tsx.snap +26 -0
  321. package/src/user-event/type/__tests__/type.test.tsx +63 -0
  322. package/src/user-event/type/index.ts +1 -0
  323. package/src/user-event/type/type.ts +20 -0
  324. package/src/user-event/utils/__tests__/wait.test.ts +63 -0
  325. package/src/user-event/utils/events.ts +54 -0
  326. package/src/user-event/utils/index.ts +2 -0
  327. package/src/user-event/utils/wait.ts +15 -0
  328. package/src/waitFor.ts +228 -0
  329. package/src/waitForElementToBeRemoved.ts +42 -0
  330. package/src/within.ts +30 -0
  331. package/tsconfig.json +17 -0
  332. package/tsconfig.release.json +8 -0
  333. package/website/.gitignore +20 -0
  334. package/website/README.md +33 -0
  335. package/website/docker/.dockerignore +3 -0
  336. package/website/docker/Dockerfile +9 -0
  337. package/website/docker/docker-compose.yml +11 -0
  338. package/website/docs/API.md +946 -0
  339. package/website/docs/EslintPLluginTestingLibrary.md +28 -0
  340. package/website/docs/FAQ.md +44 -0
  341. package/website/docs/GettingStarted.md +100 -0
  342. package/website/docs/HowShouldIQuery.md +21 -0
  343. package/website/docs/MigrationV11.md +64 -0
  344. package/website/docs/MigrationV12.md +67 -0
  345. package/website/docs/MigrationV2.md +126 -0
  346. package/website/docs/MigrationV7.md +119 -0
  347. package/website/docs/MigrationV9.md +67 -0
  348. package/website/docs/Queries.md +567 -0
  349. package/website/docs/ReactNavigation.md +371 -0
  350. package/website/docs/ReduxIntegration.md +137 -0
  351. package/website/docs/TestingEnvironment.md +154 -0
  352. package/website/docs/Troubleshooting.md +44 -0
  353. package/website/docs/UnderstandingAct.md +227 -0
  354. package/website/docs/UserEvent.md +66 -0
  355. package/website/docusaurus.config.js +114 -0
  356. package/website/package.json +31 -0
  357. package/website/sidebars.js +20 -0
  358. package/website/src/components/Feature.js +31 -0
  359. package/website/src/css/custom.css +13 -0
  360. package/website/src/css/index.module.css +77 -0
  361. package/website/src/pages/index.js +82 -0
  362. package/website/static/.nojekyll +0 -0
  363. package/website/static/css/custom.css +28 -0
  364. package/website/static/img/hit.png +0 -0
  365. package/website/static/img/locomotive.png +0 -0
  366. package/website/static/img/owl.png +0 -0
  367. package/website/static/img/tools.png +0 -0
  368. package/website/yarn.lock +7669 -0
  369. package/yarn.lock +7765 -0
  370. package/build/flushMicroTasks.d.ts +0 -5
  371. package/build/flushMicroTasks.js +0 -17
  372. package/build/flushMicroTasks.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"waitFor.js","names":["_act","_interopRequireWildcard","require","_config","_flushMicroTasks","_errors","_timers","_reactVersions","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","DEFAULT_INTERVAL","waitForInternal","expectation","timeout","getConfig","asyncUtilTimeout","interval","stackTraceError","onTimeout","TypeError","Promise","resolve","reject","lastError","intervalId","finished","promiseStatus","overallTimeoutTimer","usingFakeTimers","jestFakeTimersAreEnabled","checkExpectation","fakeTimeRemaining","error","Error","copyStackTrace","handleTimeout","jest","advanceTimersByTime","setImmediate","setTimeout","setInterval","checkRealTimersCallback","onDone","done","clearTimeout","clearInterval","type","result","then","promiseResult","resolvedValue","rejectedValue","String","waitFor","options","ErrorWithStack","optionsWithStackTrace","checkReactVersionAtLeast","previousActEnvironment","getIsReactActEnvironment","setReactActEnvironment","flushMicroTasks","act"],"sources":["../src/waitFor.ts"],"sourcesContent":["/* globals jest */\nimport act, { setReactActEnvironment, getIsReactActEnvironment } from './act';\nimport { getConfig } from './config';\nimport { flushMicroTasks } from './flushMicroTasks';\nimport { ErrorWithStack, copyStackTrace } from './helpers/errors';\nimport {\n setTimeout,\n clearTimeout,\n setImmediate,\n jestFakeTimersAreEnabled,\n} from './helpers/timers';\nimport { checkReactVersionAtLeast } from './react-versions';\n\nconst DEFAULT_INTERVAL = 50;\n\nexport type WaitForOptions = {\n timeout?: number;\n interval?: number;\n stackTraceError?: ErrorWithStack;\n onTimeout?: (error: Error) => Error;\n};\n\nfunction waitForInternal<T>(\n expectation: () => T,\n {\n timeout = getConfig().asyncUtilTimeout,\n interval = DEFAULT_INTERVAL,\n stackTraceError,\n onTimeout,\n }: WaitForOptions\n): Promise<T> {\n if (typeof expectation !== 'function') {\n throw new TypeError('Received `expectation` arg must be a function');\n }\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let lastError: unknown, intervalId: ReturnType<typeof setTimeout>;\n let finished = false;\n let promiseStatus = 'idle';\n\n let overallTimeoutTimer: NodeJS.Timeout | null = null;\n\n const usingFakeTimers = jestFakeTimersAreEnabled();\n\n if (usingFakeTimers) {\n checkExpectation();\n // this is a dangerous rule to disable because it could lead to an\n // infinite loop. However, eslint isn't smart enough to know that we're\n // setting finished inside `onDone` which will be called when we're done\n // waiting or when we've timed out.\n // eslint-disable-next-line no-unmodified-loop-condition\n let fakeTimeRemaining = timeout;\n while (!finished) {\n if (!jestFakeTimersAreEnabled()) {\n const error = new Error(\n `Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`\n );\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n reject(error);\n return;\n }\n\n // when fake timers are used we want to simulate the interval time passing\n if (fakeTimeRemaining <= 0) {\n handleTimeout();\n return;\n } else {\n fakeTimeRemaining -= interval;\n }\n\n // we *could* (maybe should?) use `advanceTimersToNextTimer` but it's\n // possible that could make this loop go on forever if someone is using\n // third party code that's setting up recursive timers so rapidly that\n // the user's timer's don't get a chance to resolve. So we'll advance\n // by an interval instead. (We have a test for this case).\n jest.advanceTimersByTime(interval);\n\n // It's really important that checkExpectation is run *before* we flush\n // in-flight promises. To be honest, I'm not sure why, and I can't quite\n // think of a way to reproduce the problem in a test, but I spent\n // an entire day banging my head against a wall on this.\n checkExpectation();\n\n // In this rare case, we *need* to wait for in-flight promises\n // to resolve before continuing. We don't need to take advantage\n // of parallelization so we're fine.\n // https://stackoverflow.com/a/59243586/971592\n // eslint-disable-next-line no-await-in-loop\n await new Promise((resolve) => setImmediate(resolve));\n }\n } else {\n overallTimeoutTimer = setTimeout(handleTimeout, timeout);\n intervalId = setInterval(checkRealTimersCallback, interval);\n checkExpectation();\n }\n\n function onDone(\n done: { type: 'result'; result: T } | { type: 'error'; error: unknown }\n ) {\n finished = true;\n if (overallTimeoutTimer) {\n clearTimeout(overallTimeoutTimer);\n }\n\n if (!usingFakeTimers) {\n clearInterval(intervalId);\n }\n\n if (done.type === 'error') {\n reject(done.error);\n } else {\n resolve(done.result);\n }\n }\n\n function checkRealTimersCallback() {\n if (jestFakeTimersAreEnabled()) {\n const error = new Error(\n `Changed from using real timers to fake timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to fake timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`\n );\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n return reject(error);\n } else {\n return checkExpectation();\n }\n }\n\n function checkExpectation() {\n if (promiseStatus === 'pending') return;\n try {\n const result = expectation();\n\n // @ts-ignore result can be a promise\n // eslint-disable-next-line promise/prefer-await-to-then\n if (typeof result?.then === 'function') {\n const promiseResult: Promise<T> = result as any;\n promiseStatus = 'pending';\n // eslint-disable-next-line promise/catch-or-return, promise/prefer-await-to-then\n promiseResult.then(\n (resolvedValue) => {\n promiseStatus = 'resolved';\n onDone({ type: 'result', result: resolvedValue });\n return;\n },\n (rejectedValue) => {\n promiseStatus = 'rejected';\n lastError = rejectedValue;\n return;\n }\n );\n } else {\n onDone({ type: 'result', result: result });\n }\n // If `callback` throws, wait for the next mutation, interval, or timeout.\n } catch (error) {\n // Save the most recent callback error to reject the promise with it in the event of a timeout\n lastError = error;\n }\n }\n\n function handleTimeout() {\n let error: Error;\n if (lastError) {\n if (lastError instanceof Error) {\n error = lastError;\n } else {\n error = new Error(String(lastError));\n }\n\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n } else {\n error = new Error('Timed out in waitFor.');\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n }\n if (typeof onTimeout === 'function') {\n const result = onTimeout(error);\n if (result) {\n error = result;\n }\n }\n onDone({ type: 'error', error });\n }\n });\n}\n\nexport default async function waitFor<T>(\n expectation: () => T,\n options?: WaitForOptions\n): Promise<T> {\n // Being able to display a useful stack trace requires generating it before doing anything async\n const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', waitFor);\n const optionsWithStackTrace = { stackTraceError, ...options };\n\n if (checkReactVersionAtLeast(18, 0)) {\n const previousActEnvironment = getIsReactActEnvironment();\n setReactActEnvironment(false);\n\n try {\n const result = await waitForInternal(expectation, optionsWithStackTrace);\n // Flush the microtask queue before restoring the `act` environment\n await flushMicroTasks();\n return result;\n } finally {\n setReactActEnvironment(previousActEnvironment);\n }\n }\n\n if (!checkReactVersionAtLeast(16, 9)) {\n return waitForInternal(expectation, optionsWithStackTrace);\n }\n\n let result: T;\n\n await act(async () => {\n result = await waitForInternal(expectation, optionsWithStackTrace);\n });\n\n // Either we have result or `waitFor` threw error\n return result!;\n}\n"],"mappings":";;;;;;AACA,IAAAA,IAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,gBAAA,GAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AAMA,IAAAK,cAAA,GAAAL,OAAA;AAA4D,SAAAM,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GAAAG,gBAAA,GAAAD,iBAAA,KAAAF,WAAA;AAAA,SAAAR,wBAAAY,GAAA,EAAAJ,WAAA,SAAAA,WAAA,IAAAI,GAAA,IAAAA,GAAA,CAAAC,UAAA,WAAAD,GAAA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,2BAAsB,EAACF,sBAAsB,CAAC;IAChD;EACF;EAEA,IAAI,CAAC,IAAAD,uCAAwB,EAAC,EAAE,EAAE,CAAC,CAAC,EAAE;IACpC,OAAO9C,eAAe,CAACC,WAAW,EAAE4C,qBAAqB,CAAC;EAC5D;EAEA,IAAIT,MAAS;EAEb,MAAM,IAAAe,YAAG,EAAC,YAAY;IACpBf,MAAM,GAAG,MAAMpC,eAAe,CAACC,WAAW,EAAE4C,qBAAqB,CAAC;EACpE,CAAC,CAAC;;EAEF;EACA,OAAOT,MAAM;AACf"}
1
+ {"version":3,"file":"waitFor.js","names":["_act","_interopRequireWildcard","require","_config","_flushMicroTasks","_errors","_timers","_reactVersions","_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","obj","__esModule","default","cache","has","get","newObj","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","DEFAULT_INTERVAL","waitForInternal","expectation","timeout","getConfig","asyncUtilTimeout","interval","stackTraceError","onTimeout","TypeError","Promise","resolve","reject","lastError","intervalId","finished","promiseStatus","overallTimeoutTimer","usingFakeTimers","jestFakeTimersAreEnabled","checkExpectation","fakeTimeRemaining","error","Error","copyStackTrace","handleTimeout","jest","advanceTimersByTime","flushMicroTasks","setTimeout","setInterval","checkRealTimersCallback","onDone","done","clearTimeout","clearInterval","type","result","then","promiseResult","resolvedValue","rejectedValue","String","waitFor","options","ErrorWithStack","optionsWithStackTrace","checkReactVersionAtLeast","previousActEnvironment","getIsReactActEnvironment","setReactActEnvironment","flushMicroTasksLegacy","act"],"sources":["../src/waitFor.ts"],"sourcesContent":["/* globals jest */\nimport act, { setReactActEnvironment, getIsReactActEnvironment } from './act';\nimport { getConfig } from './config';\nimport { flushMicroTasks, flushMicroTasksLegacy } from './flush-micro-tasks';\nimport { ErrorWithStack, copyStackTrace } from './helpers/errors';\nimport {\n setTimeout,\n clearTimeout,\n jestFakeTimersAreEnabled,\n} from './helpers/timers';\nimport { checkReactVersionAtLeast } from './react-versions';\n\nconst DEFAULT_INTERVAL = 50;\n\nexport type WaitForOptions = {\n timeout?: number;\n interval?: number;\n stackTraceError?: ErrorWithStack;\n onTimeout?: (error: Error) => Error;\n};\n\nfunction waitForInternal<T>(\n expectation: () => T,\n {\n timeout = getConfig().asyncUtilTimeout,\n interval = DEFAULT_INTERVAL,\n stackTraceError,\n onTimeout,\n }: WaitForOptions\n): Promise<T> {\n if (typeof expectation !== 'function') {\n throw new TypeError('Received `expectation` arg must be a function');\n }\n\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let lastError: unknown, intervalId: ReturnType<typeof setTimeout>;\n let finished = false;\n let promiseStatus = 'idle';\n\n let overallTimeoutTimer: NodeJS.Timeout | null = null;\n\n const usingFakeTimers = jestFakeTimersAreEnabled();\n\n if (usingFakeTimers) {\n checkExpectation();\n // this is a dangerous rule to disable because it could lead to an\n // infinite loop. However, eslint isn't smart enough to know that we're\n // setting finished inside `onDone` which will be called when we're done\n // waiting or when we've timed out.\n // eslint-disable-next-line no-unmodified-loop-condition\n let fakeTimeRemaining = timeout;\n while (!finished) {\n if (!jestFakeTimersAreEnabled()) {\n const error = new Error(\n `Changed from using fake timers to real timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to real timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`\n );\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n reject(error);\n return;\n }\n\n // when fake timers are used we want to simulate the interval time passing\n if (fakeTimeRemaining <= 0) {\n handleTimeout();\n return;\n } else {\n fakeTimeRemaining -= interval;\n }\n\n // we *could* (maybe should?) use `advanceTimersToNextTimer` but it's\n // possible that could make this loop go on forever if someone is using\n // third party code that's setting up recursive timers so rapidly that\n // the user's timer's don't get a chance to resolve. So we'll advance\n // by an interval instead. (We have a test for this case).\n jest.advanceTimersByTime(interval);\n\n // It's really important that checkExpectation is run *before* we flush\n // in-flight promises. To be honest, I'm not sure why, and I can't quite\n // think of a way to reproduce the problem in a test, but I spent\n // an entire day banging my head against a wall on this.\n checkExpectation();\n\n // In this rare case, we *need* to wait for in-flight promises\n // to resolve before continuing. We don't need to take advantage\n // of parallelization so we're fine.\n // https://stackoverflow.com/a/59243586/971592\n // eslint-disable-next-line no-await-in-loop\n await flushMicroTasks();\n }\n } else {\n overallTimeoutTimer = setTimeout(handleTimeout, timeout);\n intervalId = setInterval(checkRealTimersCallback, interval);\n checkExpectation();\n }\n\n function onDone(\n done: { type: 'result'; result: T } | { type: 'error'; error: unknown }\n ) {\n finished = true;\n if (overallTimeoutTimer) {\n clearTimeout(overallTimeoutTimer);\n }\n\n if (!usingFakeTimers) {\n clearInterval(intervalId);\n }\n\n if (done.type === 'error') {\n reject(done.error);\n } else {\n resolve(done.result);\n }\n }\n\n function checkRealTimersCallback() {\n if (jestFakeTimersAreEnabled()) {\n const error = new Error(\n `Changed from using real timers to fake timers while using waitFor. This is not allowed and will result in very strange behavior. Please ensure you're awaiting all async things your test is doing before changing to fake timers. For more info, please go to https://github.com/testing-library/dom-testing-library/issues/830`\n );\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n return reject(error);\n } else {\n return checkExpectation();\n }\n }\n\n function checkExpectation() {\n if (promiseStatus === 'pending') return;\n try {\n const result = expectation();\n\n // @ts-ignore result can be a promise\n // eslint-disable-next-line promise/prefer-await-to-then\n if (typeof result?.then === 'function') {\n const promiseResult: Promise<T> = result as any;\n promiseStatus = 'pending';\n // eslint-disable-next-line promise/catch-or-return, promise/prefer-await-to-then\n promiseResult.then(\n (resolvedValue) => {\n promiseStatus = 'resolved';\n onDone({ type: 'result', result: resolvedValue });\n return;\n },\n (rejectedValue) => {\n promiseStatus = 'rejected';\n lastError = rejectedValue;\n return;\n }\n );\n } else {\n onDone({ type: 'result', result: result });\n }\n // If `callback` throws, wait for the next mutation, interval, or timeout.\n } catch (error) {\n // Save the most recent callback error to reject the promise with it in the event of a timeout\n lastError = error;\n }\n }\n\n function handleTimeout() {\n let error: Error;\n if (lastError) {\n if (lastError instanceof Error) {\n error = lastError;\n } else {\n error = new Error(String(lastError));\n }\n\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n } else {\n error = new Error('Timed out in waitFor.');\n if (stackTraceError) {\n copyStackTrace(error, stackTraceError);\n }\n }\n if (typeof onTimeout === 'function') {\n const result = onTimeout(error);\n if (result) {\n error = result;\n }\n }\n onDone({ type: 'error', error });\n }\n });\n}\n\nexport default async function waitFor<T>(\n expectation: () => T,\n options?: WaitForOptions\n): Promise<T> {\n // Being able to display a useful stack trace requires generating it before doing anything async\n const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', waitFor);\n const optionsWithStackTrace = { stackTraceError, ...options };\n\n if (checkReactVersionAtLeast(18, 0)) {\n const previousActEnvironment = getIsReactActEnvironment();\n setReactActEnvironment(false);\n\n try {\n const result = await waitForInternal(expectation, optionsWithStackTrace);\n // Flush the microtask queue before restoring the `act` environment\n await flushMicroTasksLegacy();\n return result;\n } finally {\n setReactActEnvironment(previousActEnvironment);\n }\n }\n\n if (!checkReactVersionAtLeast(16, 9)) {\n return waitForInternal(expectation, optionsWithStackTrace);\n }\n\n let result: T;\n\n await act(async () => {\n result = await waitForInternal(expectation, optionsWithStackTrace);\n });\n\n // Either we have result or `waitFor` threw error\n return result!;\n}\n"],"mappings":";;;;;;AACA,IAAAA,IAAA,GAAAC,uBAAA,CAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,gBAAA,GAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AACA,IAAAI,OAAA,GAAAJ,OAAA;AAKA,IAAAK,cAAA,GAAAL,OAAA;AAA4D,SAAAM,yBAAAC,WAAA,eAAAC,OAAA,kCAAAC,iBAAA,OAAAD,OAAA,QAAAE,gBAAA,OAAAF,OAAA,YAAAF,wBAAA,YAAAA,CAAAC,WAAA,WAAAA,WAAA,GA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AAI;MACF,MAAMb,MAAM,GAAG,MAAMpC,eAAe,CAACC,WAAW,EAAE4C,qBAAqB,CAAC;MACxE;MACA,MAAM,IAAAK,sCAAqB,EAAC,CAAC;MAC7B,OAAOd,MAAM;IACf,CAAC,SAAS;MACR,IAAAa,2BAAsB,EAACF,sBAAsB,CAAC;IAChD;EACF;EAEA,IAAI,CAAC,IAAAD,uCAAwB,EAAC,EAAE,EAAE,CAAC,CAAC,EAAE;IACpC,OAAO9C,eAAe,CAACC,WAAW,EAAE4C,qBAAqB,CAAC;EAC5D;EAEA,IAAIT,MAAS;EAEb,MAAM,IAAAe,YAAG,EAAC,YAAY;IACpBf,MAAM,GAAG,MAAMpC,eAAe,CAACC,WAAW,EAAE4C,qBAAqB,CAAC;EACpE,CAAC,CAAC;;EAEF;EACA,OAAOT,MAAM;AACf"}
@@ -1 +1 @@
1
- {"version":3,"file":"waitForElementToBeRemoved.js","names":["_waitFor","_interopRequireDefault","require","_errors","obj","__esModule","default","isRemoved","result","Array","isArray","length","waitForElementToBeRemoved","expectation","options","timeoutError","ErrorWithStack","initialElements","waitFor","error"],"sources":["../src/waitForElementToBeRemoved.ts"],"sourcesContent":["import waitFor from './waitFor';\nimport type { WaitForOptions } from './waitFor';\nimport { ErrorWithStack } from './helpers/errors';\n\nfunction isRemoved<T>(result: T): boolean {\n return !result || (Array.isArray(result) && !result.length);\n}\n\nexport default async function waitForElementToBeRemoved<T>(\n expectation: () => T,\n options?: WaitForOptions\n): Promise<T> {\n // Created here so we get a nice stacktrace\n const timeoutError = new ErrorWithStack(\n 'Timed out in waitForElementToBeRemoved.',\n waitForElementToBeRemoved\n );\n\n // Elements have to be present initally and then removed.\n const initialElements = expectation();\n if (isRemoved(initialElements)) {\n throw new ErrorWithStack(\n 'The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.',\n waitForElementToBeRemoved\n );\n }\n\n return waitFor(() => {\n let result;\n try {\n result = expectation();\n } catch (error) {\n return initialElements;\n }\n\n if (!isRemoved(result)) {\n throw timeoutError;\n }\n\n return initialElements;\n }, options);\n}\n"],"mappings":";;;;;;AAAA,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,OAAA,GAAAD,OAAA;AAAkD,SAAAD,uBAAAG,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAElD,SAASG,SAASA,CAAIC,MAAS,EAAW;EACxC,OAAO,CAACA,MAAM,IAAKC,KAAK,CAACC,OAAO,CAACF,MAAM,CAAC,IAAI,CAACA,MAAM,CAACG,MAAO;AAC7D;AAEe,eAAeC,yBAAyBA,CACrDC,WAAoB,EACpBC,OAAwB,EACZ;EACZ;EACA,MAAMC,YAAY,GAAG,IAAIC,sBAAc,CACrC,yCAAyC,EACzCJ,yBAAyB,CAC1B;;EAED;EACA,MAAMK,eAAe,GAAGJ,WAAW,EAAE;EACrC,IAAIN,SAAS,CAACU,eAAe,CAAC,EAAE;IAC9B,MAAM,IAAID,sBAAc,CACtB,oKAAoK,EACpKJ,yBAAyB,CAC1B;EACH;EAEA,OAAO,IAAAM,gBAAO,EAAC,MAAM;IACnB,IAAIV,MAAM;IACV,IAAI;MACFA,MAAM,GAAGK,WAAW,EAAE;IACxB,CAAC,CAAC,OAAOM,KAAK,EAAE;MACd,OAAOF,eAAe;IACxB;IAEA,IAAI,CAACV,SAAS,CAACC,MAAM,CAAC,EAAE;MACtB,MAAMO,YAAY;IACpB;IAEA,OAAOE,eAAe;EACxB,CAAC,EAAEH,OAAO,CAAC;AACb"}
1
+ {"version":3,"file":"waitForElementToBeRemoved.js","names":["_waitFor","_interopRequireDefault","require","_errors","obj","__esModule","default","isRemoved","result","Array","isArray","length","waitForElementToBeRemoved","expectation","options","timeoutError","ErrorWithStack","initialElements","waitFor","error"],"sources":["../src/waitForElementToBeRemoved.ts"],"sourcesContent":["import waitFor from './waitFor';\nimport type { WaitForOptions } from './waitFor';\nimport { ErrorWithStack } from './helpers/errors';\n\nfunction isRemoved<T>(result: T): boolean {\n return !result || (Array.isArray(result) && !result.length);\n}\n\nexport default async function waitForElementToBeRemoved<T>(\n expectation: () => T,\n options?: WaitForOptions\n): Promise<T> {\n // Created here so we get a nice stacktrace\n const timeoutError = new ErrorWithStack(\n 'Timed out in waitForElementToBeRemoved.',\n waitForElementToBeRemoved\n );\n\n // Elements have to be present initally and then removed.\n const initialElements = expectation();\n if (isRemoved(initialElements)) {\n throw new ErrorWithStack(\n 'The element(s) given to waitForElementToBeRemoved are already removed. waitForElementToBeRemoved requires that the element(s) exist(s) before waiting for removal.',\n waitForElementToBeRemoved\n );\n }\n\n return waitFor(() => {\n let result;\n try {\n result = expectation();\n } catch (error) {\n return initialElements;\n }\n\n if (!isRemoved(result)) {\n throw timeoutError;\n }\n\n return initialElements;\n }, options);\n}\n"],"mappings":";;;;;;AAAA,IAAAA,QAAA,GAAAC,sBAAA,CAAAC,OAAA;AAEA,IAAAC,OAAA,GAAAD,OAAA;AAAkD,SAAAD,uBAAAG,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAElD,SAASG,SAASA,CAAIC,MAAS,EAAW;EACxC,OAAO,CAACA,MAAM,IAAKC,KAAK,CAACC,OAAO,CAACF,MAAM,CAAC,IAAI,CAACA,MAAM,CAACG,MAAO;AAC7D;AAEe,eAAeC,yBAAyBA,CACrDC,WAAoB,EACpBC,OAAwB,EACZ;EACZ;EACA,MAAMC,YAAY,GAAG,IAAIC,sBAAc,CACrC,yCAAyC,EACzCJ,yBACF,CAAC;;EAED;EACA,MAAMK,eAAe,GAAGJ,WAAW,CAAC,CAAC;EACrC,IAAIN,SAAS,CAACU,eAAe,CAAC,EAAE;IAC9B,MAAM,IAAID,sBAAc,CACtB,oKAAoK,EACpKJ,yBACF,CAAC;EACH;EAEA,OAAO,IAAAM,gBAAO,EAAC,MAAM;IACnB,IAAIV,MAAM;IACV,IAAI;MACFA,MAAM,GAAGK,WAAW,CAAC,CAAC;IACxB,CAAC,CAAC,OAAOM,KAAK,EAAE;MACd,OAAOF,eAAe;IACxB;IAEA,IAAI,CAACV,SAAS,CAACC,MAAM,CAAC,EAAE;MACtB,MAAMO,YAAY;IACpB;IAEA,OAAOE,eAAe;EACxB,CAAC,EAAEH,OAAO,CAAC;AACb"}
@@ -0,0 +1,4 @@
1
+ {
2
+ "12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true,
3
+ "40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true
4
+ }
@@ -0,0 +1,14 @@
1
+ node_modules/
2
+ .expo/
3
+ dist/
4
+ npm-debug.*
5
+ *.jks
6
+ *.p8
7
+ *.p12
8
+ *.key
9
+ *.mobileprovision
10
+ *.orig.*
11
+ web-build/
12
+
13
+ # macOS
14
+ .DS_Store
@@ -0,0 +1,20 @@
1
+ import * as React from 'react';
2
+ import { SafeAreaView } from 'react-native';
3
+ import { LoginForm } from './components/LoginForm';
4
+ import { Home } from './components/Home';
5
+
6
+ const App = () => {
7
+ const [user, setUser] = React.useState<string | null>(null);
8
+
9
+ return (
10
+ <SafeAreaView>
11
+ {user == null ? (
12
+ <LoginForm onLoginSuccess={setUser} />
13
+ ) : (
14
+ <Home user={user} />
15
+ )}
16
+ </SafeAreaView>
17
+ );
18
+ };
19
+
20
+ export default App;
@@ -0,0 +1,11 @@
1
+ # Basic RNTL setup
2
+
3
+ This example is shows a basic modern React Native Testing Library setup in a template Expo app.
4
+
5
+ The app and related tests written in TypeScript, and it uses recommended practices like:
6
+
7
+ - testing large pieces of application instead of small components
8
+ - using `screen`-based queries
9
+ - using recommended query types, e.g. `*ByText`, `*ByLabelText`, `*ByPlaceholderText` over `byTestId`
10
+
11
+ You also use this repository as a reference when having issues in your RNTL configuration, as it contains the recommended Jest setup.
@@ -0,0 +1,119 @@
1
+ import * as React from 'react';
2
+ import { render, screen, fireEvent } from '@testing-library/react-native';
3
+ import App from '../App';
4
+
5
+ /**
6
+ * A good place to start is having a tests that your component renders correctly.
7
+ */
8
+ test('renders correctly', () => {
9
+ // Idiom: no need to capture render output, as we will use `screen` for queries.
10
+ render(<App />);
11
+
12
+ // Idiom: `getBy*` queries are predicates by themselves, but we will use it with `expect().toBeOnTheScreen()`
13
+ // to clarify our intent.
14
+ expect(
15
+ screen.getByRole('header', { name: 'Sign in to Example App' })
16
+ ).toBeOnTheScreen();
17
+ });
18
+
19
+ /**
20
+ * Hint: It's best when your tests are similar to what a manual test scenarions would look like,
21
+ * i.e. a series of actions taken by the user, followed by a series of assertions verified from
22
+ * his point of view.
23
+ */
24
+ test('User can sign in successully with correct credentials', async () => {
25
+ // Idiom: no need to capture render output, as we will use `screen` for queries.
26
+ render(<App />);
27
+
28
+ // Idiom: `getBy*` queries are predicates by themselves, but we will use it with `expect().toBeOnTheScreen()`
29
+ // to clarify our intent.
30
+ expect(
31
+ screen.getByRole('header', { name: 'Sign in to Example App' })
32
+ ).toBeOnTheScreen();
33
+
34
+ // Hint: we can use `getByLabelText` to find our text inputs using their labels.
35
+ fireEvent.changeText(screen.getByLabelText('Username'), 'admin');
36
+ fireEvent.changeText(screen.getByLabelText('Password'), 'admin1');
37
+
38
+ // Hint: we can use `getByRole` to find our button with given text.
39
+ fireEvent.press(screen.getByRole('button', { name: 'Sign In' }));
40
+
41
+ // Idiom: since pressing button triggers async operation we need to use `findBy*` query to wait
42
+ // for the action to complete.
43
+ // Hint: subsequent queries do not need to use `findBy*`, because they are used after the async action
44
+ // already finished
45
+ expect(
46
+ await screen.findByRole('header', { name: 'Welcome admin!' })
47
+ ).toBeOnTheScreen();
48
+
49
+ // Idiom: use `queryBy*` with `expect().not.toBeOnTheScreen()` to assess that element is not present.
50
+ expect(
51
+ screen.queryByRole('header', { name: 'Sign in to Example App' })
52
+ ).not.toBeOnTheScreen();
53
+ expect(screen.queryByLabelText('Username')).not.toBeOnTheScreen();
54
+ expect(screen.queryByLabelText('Password')).not.toBeOnTheScreen();
55
+ });
56
+
57
+ /**
58
+ * Another test case based on manual test scenario.
59
+ *
60
+ * Hint: Try to tests what a user would see and do, instead of assering internal component state
61
+ * that is not directly reflected in the UI.
62
+ *
63
+ * For this reason prefer quries that correspond to things directly observable by the user like:
64
+ * `getByRole`, `getByText`, `getByLabelText`, `getByPlaceholderText, `getByDisplayValue`, etc.
65
+ * over `getByTestId` which is not directly observable by the user.
66
+ *
67
+ * Note: that some times you will have to resort to `getByTestId`, but treat it as a last resort.
68
+ */
69
+ test('User will see errors for incorrect credentials', async () => {
70
+ render(<App />);
71
+
72
+ expect(
73
+ screen.getByRole('header', { name: 'Sign in to Example App' })
74
+ ).toBeOnTheScreen();
75
+
76
+ fireEvent.changeText(screen.getByLabelText('Username'), 'admin');
77
+ fireEvent.changeText(screen.getByLabelText('Password'), 'qwerty123');
78
+ fireEvent.press(screen.getByRole('button', { name: 'Sign In' }));
79
+
80
+ // Hint: you can use custom Jest Native matcher to check text content.
81
+ expect(await screen.findByRole('alert')).toHaveTextContent(
82
+ 'Incorrect username or password'
83
+ );
84
+
85
+ expect(
86
+ screen.getByRole('header', { name: 'Sign in to Example App' })
87
+ ).toBeOnTheScreen();
88
+ expect(screen.getByLabelText('Username')).toBeOnTheScreen();
89
+ expect(screen.getByLabelText('Password')).toBeOnTheScreen();
90
+ });
91
+
92
+ /**
93
+ * Do not be afraid to write longer test scenarios, with repeating act and assert statements.
94
+ */
95
+ test('User can sign in after incorrect attempt', async () => {
96
+ render(<App />);
97
+
98
+ expect(
99
+ screen.getByRole('header', { name: 'Sign in to Example App' })
100
+ ).toBeOnTheScreen();
101
+
102
+ fireEvent.changeText(screen.getByLabelText('Username'), 'admin');
103
+ fireEvent.changeText(screen.getByLabelText('Password'), 'qwerty123');
104
+ fireEvent.press(screen.getByRole('button', { name: 'Sign In' }));
105
+
106
+ expect(await screen.findByRole('alert')).toHaveTextContent(
107
+ 'Incorrect username or password'
108
+ );
109
+
110
+ fireEvent.changeText(screen.getByLabelText('Password'), 'admin1');
111
+ fireEvent.press(screen.getByRole('button', { name: 'Sign In' }));
112
+
113
+ expect(await screen.findByText('Welcome admin!')).toBeOnTheScreen();
114
+ expect(
115
+ screen.queryByRole('header', { name: 'Sign in to Example App' })
116
+ ).not.toBeOnTheScreen();
117
+ expect(screen.queryByLabelText('Username')).not.toBeOnTheScreen();
118
+ expect(screen.queryByLabelText('Password')).not.toBeOnTheScreen();
119
+ });
@@ -0,0 +1,31 @@
1
+ {
2
+ "expo": {
3
+ "name": "RNTL Example Basic",
4
+ "slug": "rntl-example-basic",
5
+ "version": "1.0.0",
6
+ "orientation": "portrait",
7
+ "icon": "./assets/icon.png",
8
+ "userInterfaceStyle": "light",
9
+ "splash": {
10
+ "image": "./assets/splash.png",
11
+ "resizeMode": "contain",
12
+ "backgroundColor": "#ffffff"
13
+ },
14
+ "updates": {
15
+ "fallbackToCacheTimeout": 0
16
+ },
17
+ "assetBundlePatterns": ["**/*"],
18
+ "ios": {
19
+ "supportsTablet": true
20
+ },
21
+ "android": {
22
+ "adaptiveIcon": {
23
+ "foregroundImage": "./assets/adaptive-icon.png",
24
+ "backgroundColor": "#FFFFFF"
25
+ }
26
+ },
27
+ "web": {
28
+ "favicon": "./assets/favicon.png"
29
+ }
30
+ }
31
+ }
Binary file
Binary file
@@ -0,0 +1,6 @@
1
+ module.exports = function (api) {
2
+ api.cache(true);
3
+ return {
4
+ presets: ['babel-preset-expo'],
5
+ };
6
+ };
@@ -0,0 +1,28 @@
1
+ import * as React from 'react';
2
+ import { StyleSheet, View, Text } from 'react-native';
3
+
4
+ type Props = {
5
+ user: string;
6
+ };
7
+
8
+ export function Home({ user }: Props) {
9
+ return (
10
+ <View style={styles.container}>
11
+ <Text accessibilityRole="header" style={styles.title}>
12
+ Welcome {user}!
13
+ </Text>
14
+ </View>
15
+ );
16
+ }
17
+
18
+ const styles = StyleSheet.create({
19
+ container: {
20
+ padding: 20,
21
+ },
22
+ title: {
23
+ alignSelf: 'center',
24
+ fontSize: 24,
25
+ marginTop: 8,
26
+ marginBottom: 40,
27
+ },
28
+ });
@@ -0,0 +1,138 @@
1
+ import * as React from 'react';
2
+ import {
3
+ StyleSheet,
4
+ View,
5
+ Text,
6
+ TextInput,
7
+ Pressable,
8
+ ActivityIndicator,
9
+ } from 'react-native';
10
+
11
+ type Props = {
12
+ onLoginSuccess: (user: string) => void;
13
+ };
14
+
15
+ export function LoginForm({ onLoginSuccess }: Props) {
16
+ const [username, setUsername] = React.useState('');
17
+ const [password, setPassword] = React.useState('');
18
+ const [error, setError] = React.useState<string | undefined>();
19
+ const [isLoading, setIsLoading] = React.useState(false);
20
+
21
+ const handleSignIn = async () => {
22
+ setIsLoading(true);
23
+
24
+ const user = await authUser(username, password);
25
+ setIsLoading(false);
26
+
27
+ if (user) {
28
+ setError(undefined);
29
+ onLoginSuccess(user);
30
+ } else {
31
+ setError('Incorrect username or password');
32
+ }
33
+ };
34
+
35
+ return (
36
+ <View style={styles.container}>
37
+ <Text accessibilityRole="header" style={styles.title}>
38
+ Sign in to Example App
39
+ </Text>
40
+
41
+ <Text style={styles.textLabel}>Username</Text>
42
+ <TextInput
43
+ value={username}
44
+ onChangeText={setUsername}
45
+ accessibilityLabel="Username"
46
+ autoCapitalize="none"
47
+ style={styles.textInput}
48
+ />
49
+
50
+ <Text style={styles.textLabel}>Password</Text>
51
+ <TextInput
52
+ value={password}
53
+ onChangeText={setPassword}
54
+ accessibilityLabel="Password"
55
+ secureTextEntry={true}
56
+ style={styles.textInput}
57
+ />
58
+
59
+ {error && (
60
+ <Text accessibilityRole="alert" style={styles.validator}>
61
+ {error}
62
+ </Text>
63
+ )}
64
+
65
+ <Pressable
66
+ accessibilityRole="button"
67
+ disabled={isLoading}
68
+ onPress={handleSignIn}
69
+ style={styles.button}
70
+ >
71
+ {isLoading ? (
72
+ <ActivityIndicator color="white" />
73
+ ) : (
74
+ <Text style={styles.buttonText}>Sign In</Text>
75
+ )}
76
+ </Pressable>
77
+ </View>
78
+ );
79
+ }
80
+
81
+ /**
82
+ * Fake authentication function according to our abilities.
83
+ * @param username The username to authenticate.
84
+ * @param password The password to authenticate.
85
+ * @returns username if the username and password are correct, null otherwise.
86
+ */
87
+ async function authUser(
88
+ username: string,
89
+ password: string
90
+ ): Promise<string | null> {
91
+ return new Promise((resolve) =>
92
+ setTimeout(() => {
93
+ const hasValidCredentials = username === 'admin' && password === 'admin1';
94
+ resolve(hasValidCredentials ? username : null);
95
+ }, 250)
96
+ );
97
+ }
98
+
99
+ const styles = StyleSheet.create({
100
+ container: {
101
+ padding: 20,
102
+ },
103
+ title: {
104
+ alignSelf: 'center',
105
+ fontSize: 24,
106
+ marginTop: 8,
107
+ marginBottom: 40,
108
+ },
109
+ textLabel: {
110
+ fontSize: 16,
111
+ color: '#444',
112
+ },
113
+ textInput: {
114
+ fontSize: 20,
115
+ padding: 8,
116
+ marginVertical: 8,
117
+ borderColor: 'black',
118
+ borderWidth: 1,
119
+ },
120
+ button: {
121
+ backgroundColor: '#3256a8',
122
+ padding: 16,
123
+ alignItems: 'center',
124
+ justifyContent: 'center',
125
+ marginTop: 20,
126
+ minHeight: 56,
127
+ },
128
+ buttonText: {
129
+ fontSize: 20,
130
+ fontWeight: '600',
131
+ color: 'white',
132
+ },
133
+ validator: {
134
+ color: 'red',
135
+ fontSize: 18,
136
+ marginTop: 8,
137
+ },
138
+ });
@@ -0,0 +1,7 @@
1
+ /* eslint-disable no-undef, import/no-extraneous-dependencies */
2
+
3
+ // Import Jest Native matchers
4
+ import '@testing-library/jest-native/extend-expect';
5
+
6
+ // Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing
7
+ jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');
@@ -0,0 +1,5 @@
1
+ module.exports = {
2
+ preset: '@testing-library/react-native',
3
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
4
+ setupFilesAfterEnv: ['./jest-setup.ts'],
5
+ };
@@ -0,0 +1,30 @@
1
+ {
2
+ "main": "node_modules/expo/AppEntry.js",
3
+ "scripts": {
4
+ "start": "expo start",
5
+ "android": "expo start --android",
6
+ "ios": "expo start --ios",
7
+ "web": "expo start --web",
8
+ "eject": "expo eject",
9
+ "test": "jest",
10
+ "typecheck": "tsc --noEmit"
11
+ },
12
+ "dependencies": {
13
+ "expo": "^48.0.0",
14
+ "expo-status-bar": "~1.4.4",
15
+ "react": "18.2.0",
16
+ "react-dom": "18.2.0",
17
+ "react-native": "0.71.3",
18
+ "react-native-web": "~0.18.11"
19
+ },
20
+ "devDependencies": {
21
+ "@babel/core": "^7.20.0",
22
+ "@testing-library/jest-native": "^5.4.2",
23
+ "@testing-library/react-native": "^12.1.2",
24
+ "@types/react": "~18.2.6",
25
+ "jest": "^29.3.0",
26
+ "react-test-renderer": "18.2.0",
27
+ "typescript": "^5.0.4"
28
+ },
29
+ "private": true
30
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "expo/tsconfig.base",
3
+ "compilerOptions": {
4
+ "strict": true,
5
+ "allowJs": false
6
+ }
7
+ }
@@ -0,0 +1,14 @@
1
+ # RNTL example app for React Navigation
2
+
3
+ This example shows how to write integration tests using React Navigation without mocking it. Presented approach has been consulted with and influenced by React Navigation team.
4
+
5
+ ## Recommended tests
6
+
7
+ There are two types of recommeded tests:
8
+ 1. Tests operating on navigator level - these use `renderNavigator` helper to render a navigator component used in the app. It is useful when you want to test a scenario that includes multiple screens.
9
+ 2. Tests operating on single screen level - these use regular `render` helper but require refactoring screen components into `Screen` and `ScreenContent` components. Where `Screen` receives React Navigation props and/or uses hooks like `useNavigation` while `ScreenContent` does not have a direct relation to React Navigation API but gets props from `Screen` and calls relevant callbacks to trigger navigation.
10
+
11
+ ## Non-recommended tests
12
+
13
+ There also exists another popular type of screen level tests, where users mock React Navigation objects like `navigation`, `route` and/or hooks like `useNavigation`, etc. We don't recommend this way of testing. **Mocking internal parts of the libraries is effectively testing implementation details, which goes against the Testing Library's [Guiding Principles](https://testing-library.com/docs/guiding-principles/)**.
14
+
@@ -0,0 +1,4 @@
1
+ module.exports = {
2
+ presets: ['module:metro-react-native-babel-preset'],
3
+ plugins: ['react-native-reanimated/plugin'],
4
+ };
@@ -0,0 +1,11 @@
1
+ /* eslint-disable no-undef, import/no-extraneous-dependencies */
2
+
3
+ // Import Jest Native matchers
4
+ import '@testing-library/jest-native/extend-expect';
5
+
6
+ // Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing
7
+ jest.mock('react-native/Libraries/Animated/NativeAnimatedHelper');
8
+
9
+ // Setup Reanimated mocking for Drawer navigation
10
+ global.ReanimatedDataMock = { now: () => Date.now() };
11
+ require('react-native-reanimated/lib/reanimated2/jestUtils').setUpTests();
@@ -0,0 +1,10 @@
1
+ module.exports = {
2
+ preset: 'react-native',
3
+ setupFilesAfterEnv: [
4
+ './node_modules/react-native-gesture-handler/jestSetup.js',
5
+ './jest-setup.js',
6
+ ],
7
+ transformIgnorePatterns: [
8
+ 'node_modules/(?!(jest-)?react-native|@react-native|@react-native-community|@react-navigation)',
9
+ ],
10
+ };
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "react-navigation-example",
3
+ "description": "Testing React Navigation with RNTL",
4
+ "version": "0.0.1",
5
+ "private": true,
6
+ "scripts": {
7
+ "test": "jest"
8
+ },
9
+ "dependencies": {
10
+ "@react-navigation/bottom-tabs": "^6.4.1",
11
+ "@react-navigation/drawer": "^6.5.1",
12
+ "@react-navigation/native": "^6.0.14",
13
+ "@react-navigation/native-stack": "^6.9.2",
14
+ "@react-navigation/stack": "^6.3.5",
15
+ "react": "^18.1.0",
16
+ "react-native": "^0.70.6",
17
+ "react-native-gesture-handler": "^2.8.0",
18
+ "react-native-reanimated": "^2.13.0",
19
+ "react-native-safe-area-context": "^4.4.1",
20
+ "react-native-screens": "^3.18.2"
21
+ },
22
+ "devDependencies": {
23
+ "@babel/core": "^7.20.2",
24
+ "@testing-library/jest-native": "^5.4.0",
25
+ "@testing-library/react-native": "^11.5.0",
26
+ "babel-jest": "^29.3.1",
27
+ "jest": "^29.3.0",
28
+ "metro-react-native-babel-preset": "^0.72.3",
29
+ "react-test-renderer": "^18.1.0"
30
+ }
31
+ }
@@ -0,0 +1,21 @@
1
+ import React from 'react';
2
+ import { StatusBar, StyleSheet, View } from 'react-native';
3
+ import { NavigationContainer } from '@react-navigation/native';
4
+ import AppNavigator from './NativeStackNavigator';
5
+
6
+ export default function App() {
7
+ return (
8
+ <NavigationContainer>
9
+ <View style={styles.container}>
10
+ <StatusBar barStyle="dark-content" />
11
+ <AppNavigator />
12
+ </View>
13
+ </NavigationContainer>
14
+ );
15
+ }
16
+
17
+ const styles = StyleSheet.create({
18
+ container: {
19
+ flex: 1,
20
+ },
21
+ });
@@ -0,0 +1,15 @@
1
+ import * as React from 'react';
2
+ import { createDrawerNavigator } from '@react-navigation/drawer';
3
+ import DrawerHomeScreen from './screens/DrawerHomeScreen';
4
+ import SettingsScreen from './screens/SettingsScreen';
5
+
6
+ const Drawer = createDrawerNavigator();
7
+
8
+ export default function Navigation() {
9
+ return (
10
+ <Drawer.Navigator>
11
+ <Drawer.Screen name="Home" component={DrawerHomeScreen} />
12
+ <Drawer.Screen name="Settings" component={SettingsScreen} />
13
+ </Drawer.Navigator>
14
+ );
15
+ }