react.esm.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import * as testUtils from 'react-dom/test-utils';
  2. import * as React from 'react';
  3. import ReactDOM from 'react-dom';
  4. import * as ReactDOMClient from 'react-dom/client';
  5. import { fireEvent as fireEvent$1, configure, prettyDOM, getQueriesForElement } from '@testing-library/dom';
  6. export * from '@testing-library/dom';
  7. const domAct = testUtils.act;
  8. function getGlobalThis() {
  9. /* istanbul ignore else */
  10. if (typeof globalThis !== 'undefined') {
  11. return globalThis;
  12. }
  13. /* istanbul ignore next */
  14. if (typeof self !== 'undefined') {
  15. return self;
  16. }
  17. /* istanbul ignore next */
  18. if (typeof window !== 'undefined') {
  19. return window;
  20. }
  21. /* istanbul ignore next */
  22. if (typeof global !== 'undefined') {
  23. return global;
  24. }
  25. /* istanbul ignore next */
  26. throw new Error('unable to locate global object');
  27. }
  28. function setIsReactActEnvironment(isReactActEnvironment) {
  29. getGlobalThis().IS_REACT_ACT_ENVIRONMENT = isReactActEnvironment;
  30. }
  31. function getIsReactActEnvironment() {
  32. return getGlobalThis().IS_REACT_ACT_ENVIRONMENT;
  33. }
  34. function withGlobalActEnvironment(actImplementation) {
  35. return callback => {
  36. const previousActEnvironment = getIsReactActEnvironment();
  37. setIsReactActEnvironment(true);
  38. try {
  39. // The return value of `act` is always a thenable.
  40. let callbackNeedsToBeAwaited = false;
  41. const actResult = actImplementation(() => {
  42. const result = callback();
  43. if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
  44. callbackNeedsToBeAwaited = true;
  45. }
  46. return result;
  47. });
  48. if (callbackNeedsToBeAwaited) {
  49. const thenable = actResult;
  50. return {
  51. then: (resolve, reject) => {
  52. thenable.then(returnValue => {
  53. setIsReactActEnvironment(previousActEnvironment);
  54. resolve(returnValue);
  55. }, error => {
  56. setIsReactActEnvironment(previousActEnvironment);
  57. reject(error);
  58. });
  59. }
  60. };
  61. } else {
  62. setIsReactActEnvironment(previousActEnvironment);
  63. return actResult;
  64. }
  65. } catch (error) {
  66. // Can't be a `finally {}` block since we don't know if we have to immediately restore IS_REACT_ACT_ENVIRONMENT
  67. // or if we have to await the callback first.
  68. setIsReactActEnvironment(previousActEnvironment);
  69. throw error;
  70. }
  71. };
  72. }
  73. const act = withGlobalActEnvironment(domAct);
  74. /* eslint no-console:0 */
  75. // dom-testing-library's version of fireEvent. The reason
  76. // we make this distinction however is because we have
  77. // a few extra events that work a bit differently
  78. const fireEvent = function () {
  79. return fireEvent$1(...arguments);
  80. };
  81. Object.keys(fireEvent$1).forEach(key => {
  82. fireEvent[key] = function () {
  83. return fireEvent$1[key](...arguments);
  84. };
  85. }); // React event system tracks native mouseOver/mouseOut events for
  86. // running onMouseEnter/onMouseLeave handlers
  87. // @link https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/events/EnterLeaveEventPlugin.js#L24-L31
  88. const mouseEnter = fireEvent.mouseEnter;
  89. const mouseLeave = fireEvent.mouseLeave;
  90. fireEvent.mouseEnter = function () {
  91. mouseEnter(...arguments);
  92. return fireEvent.mouseOver(...arguments);
  93. };
  94. fireEvent.mouseLeave = function () {
  95. mouseLeave(...arguments);
  96. return fireEvent.mouseOut(...arguments);
  97. };
  98. const pointerEnter = fireEvent.pointerEnter;
  99. const pointerLeave = fireEvent.pointerLeave;
  100. fireEvent.pointerEnter = function () {
  101. pointerEnter(...arguments);
  102. return fireEvent.pointerOver(...arguments);
  103. };
  104. fireEvent.pointerLeave = function () {
  105. pointerLeave(...arguments);
  106. return fireEvent.pointerOut(...arguments);
  107. };
  108. const select = fireEvent.select;
  109. fireEvent.select = (node, init) => {
  110. select(node, init); // React tracks this event only on focused inputs
  111. node.focus(); // React creates this event when one of the following native events happens
  112. // - contextMenu
  113. // - mouseUp
  114. // - dragEnd
  115. // - keyUp
  116. // - keyDown
  117. // so we can use any here
  118. // @link https://github.com/facebook/react/blob/b87aabdfe1b7461e7331abb3601d9e6bb27544bc/packages/react-dom/src/events/SelectEventPlugin.js#L203-L224
  119. fireEvent.keyUp(node, init);
  120. }; // React event system tracks native focusout/focusin events for
  121. // running blur/focus handlers
  122. // @link https://github.com/facebook/react/pull/19186
  123. const blur = fireEvent.blur;
  124. const focus = fireEvent.focus;
  125. fireEvent.blur = function () {
  126. fireEvent.focusOut(...arguments);
  127. return blur(...arguments);
  128. };
  129. fireEvent.focus = function () {
  130. fireEvent.focusIn(...arguments);
  131. return focus(...arguments);
  132. };
  133. configure({
  134. unstable_advanceTimersWrapper: cb => {
  135. return act(cb);
  136. },
  137. // We just want to run `waitFor` without IS_REACT_ACT_ENVIRONMENT
  138. // But that's not necessarily how `asyncWrapper` is used since it's a public method.
  139. // Let's just hope nobody else is using it.
  140. asyncWrapper: async cb => {
  141. const previousActEnvironment = getIsReactActEnvironment();
  142. setIsReactActEnvironment(false);
  143. try {
  144. return await cb();
  145. } finally {
  146. setIsReactActEnvironment(previousActEnvironment);
  147. }
  148. },
  149. eventWrapper: cb => {
  150. let result;
  151. act(() => {
  152. result = cb();
  153. });
  154. return result;
  155. }
  156. }); // Ideally we'd just use a WeakMap where containers are keys and roots are values.
  157. // We use two variables so that we can bail out in constant time when we render with a new container (most common use case)
  158. /**
  159. * @type {Set<import('react-dom').Container>}
  160. */
  161. const mountedContainers = new Set();
  162. /**
  163. * @type Array<{container: import('react-dom').Container, root: ReturnType<typeof createConcurrentRoot>}>
  164. */
  165. const mountedRootEntries = [];
  166. function createConcurrentRoot(container, _ref) {
  167. let {
  168. hydrate,
  169. ui,
  170. wrapper: WrapperComponent
  171. } = _ref;
  172. let root;
  173. if (hydrate) {
  174. act(() => {
  175. root = ReactDOMClient.hydrateRoot(container, WrapperComponent ? /*#__PURE__*/React.createElement(WrapperComponent, null, ui) : ui);
  176. });
  177. } else {
  178. root = ReactDOMClient.createRoot(container);
  179. }
  180. return {
  181. hydrate() {
  182. /* istanbul ignore if */
  183. if (!hydrate) {
  184. throw new Error('Attempted to hydrate a non-hydrateable root. This is a bug in `@testing-library/react`.');
  185. } // Nothing to do since hydration happens when creating the root object.
  186. },
  187. render(element) {
  188. root.render(element);
  189. },
  190. unmount() {
  191. root.unmount();
  192. }
  193. };
  194. }
  195. function createLegacyRoot(container) {
  196. return {
  197. hydrate(element) {
  198. ReactDOM.hydrate(element, container);
  199. },
  200. render(element) {
  201. ReactDOM.render(element, container);
  202. },
  203. unmount() {
  204. ReactDOM.unmountComponentAtNode(container);
  205. }
  206. };
  207. }
  208. function renderRoot(ui, _ref2) {
  209. let {
  210. baseElement,
  211. container,
  212. hydrate,
  213. queries,
  214. root,
  215. wrapper: WrapperComponent
  216. } = _ref2;
  217. const wrapUiIfNeeded = innerElement => WrapperComponent ? /*#__PURE__*/React.createElement(WrapperComponent, null, innerElement) : innerElement;
  218. act(() => {
  219. if (hydrate) {
  220. root.hydrate(wrapUiIfNeeded(ui), container);
  221. } else {
  222. root.render(wrapUiIfNeeded(ui), container);
  223. }
  224. });
  225. return {
  226. container,
  227. baseElement,
  228. debug: function (el, maxLength, options) {
  229. if (el === void 0) {
  230. el = baseElement;
  231. }
  232. return Array.isArray(el) ? // eslint-disable-next-line no-console
  233. el.forEach(e => console.log(prettyDOM(e, maxLength, options))) : // eslint-disable-next-line no-console,
  234. console.log(prettyDOM(el, maxLength, options));
  235. },
  236. unmount: () => {
  237. act(() => {
  238. root.unmount();
  239. });
  240. },
  241. rerender: rerenderUi => {
  242. renderRoot(wrapUiIfNeeded(rerenderUi), {
  243. container,
  244. baseElement,
  245. root
  246. }); // Intentionally do not return anything to avoid unnecessarily complicating the API.
  247. // folks can use all the same utilities we return in the first place that are bound to the container
  248. },
  249. asFragment: () => {
  250. /* istanbul ignore else (old jsdom limitation) */
  251. if (typeof document.createRange === 'function') {
  252. return document.createRange().createContextualFragment(container.innerHTML);
  253. } else {
  254. const template = document.createElement('template');
  255. template.innerHTML = container.innerHTML;
  256. return template.content;
  257. }
  258. },
  259. ...getQueriesForElement(baseElement, queries)
  260. };
  261. }
  262. function render(ui, _temp) {
  263. let {
  264. container,
  265. baseElement = container,
  266. legacyRoot = false,
  267. queries,
  268. hydrate = false,
  269. wrapper
  270. } = _temp === void 0 ? {} : _temp;
  271. if (!baseElement) {
  272. // default to document.body instead of documentElement to avoid output of potentially-large
  273. // head elements (such as JSS style blocks) in debug output
  274. baseElement = document.body;
  275. }
  276. if (!container) {
  277. container = baseElement.appendChild(document.createElement('div'));
  278. }
  279. let root; // eslint-disable-next-line no-negated-condition -- we want to map the evolution of this over time. The root is created first. Only later is it re-used so we don't want to read the case that happens later first.
  280. if (!mountedContainers.has(container)) {
  281. const createRootImpl = legacyRoot ? createLegacyRoot : createConcurrentRoot;
  282. root = createRootImpl(container, {
  283. hydrate,
  284. ui,
  285. wrapper
  286. });
  287. mountedRootEntries.push({
  288. container,
  289. root
  290. }); // we'll add it to the mounted containers regardless of whether it's actually
  291. // added to document.body so the cleanup method works regardless of whether
  292. // they're passing us a custom container or not.
  293. mountedContainers.add(container);
  294. } else {
  295. mountedRootEntries.forEach(rootEntry => {
  296. // Else is unreachable since `mountedContainers` has the `container`.
  297. // Only reachable if one would accidentally add the container to `mountedContainers` but not the root to `mountedRootEntries`
  298. /* istanbul ignore else */
  299. if (rootEntry.container === container) {
  300. root = rootEntry.root;
  301. }
  302. });
  303. }
  304. return renderRoot(ui, {
  305. container,
  306. baseElement,
  307. queries,
  308. hydrate,
  309. wrapper,
  310. root
  311. });
  312. }
  313. function cleanup() {
  314. mountedRootEntries.forEach(_ref3 => {
  315. let {
  316. root,
  317. container
  318. } = _ref3;
  319. act(() => {
  320. root.unmount();
  321. });
  322. if (container.parentNode === document.body) {
  323. document.body.removeChild(container);
  324. }
  325. });
  326. mountedRootEntries.length = 0;
  327. mountedContainers.clear();
  328. }
  329. function renderHook(renderCallback, options) {
  330. if (options === void 0) {
  331. options = {};
  332. }
  333. const {
  334. initialProps,
  335. ...renderOptions
  336. } = options;
  337. const result = /*#__PURE__*/React.createRef();
  338. function TestComponent(_ref4) {
  339. let {
  340. renderCallbackProps
  341. } = _ref4;
  342. const pendingResult = renderCallback(renderCallbackProps);
  343. React.useEffect(() => {
  344. result.current = pendingResult;
  345. });
  346. return null;
  347. }
  348. const {
  349. rerender: baseRerender,
  350. unmount
  351. } = render( /*#__PURE__*/React.createElement(TestComponent, {
  352. renderCallbackProps: initialProps
  353. }), renderOptions);
  354. function rerender(rerenderCallbackProps) {
  355. return baseRerender( /*#__PURE__*/React.createElement(TestComponent, {
  356. renderCallbackProps: rerenderCallbackProps
  357. }));
  358. }
  359. return {
  360. result,
  361. rerender,
  362. unmount
  363. };
  364. } // just re-export everything from dom-testing-library
  365. /* eslint func-name-matching:0 */
  366. var _process$env;
  367. // or teardown then we'll automatically run cleanup afterEach test
  368. // this ensures that tests run in isolation from each other
  369. // if you don't like this then either import the `pure` module
  370. // or set the RTL_SKIP_AUTO_CLEANUP env variable to 'true'.
  371. if (typeof process === 'undefined' || !((_process$env = process.env) != null && _process$env.RTL_SKIP_AUTO_CLEANUP)) {
  372. // ignore teardown() in code coverage because Jest does not support it
  373. /* istanbul ignore else */
  374. if (typeof afterEach === 'function') {
  375. afterEach(() => {
  376. cleanup();
  377. });
  378. } else if (typeof teardown === 'function') {
  379. // Block is guarded by `typeof` check.
  380. // eslint does not support `typeof` guards.
  381. // eslint-disable-next-line no-undef
  382. teardown(() => {
  383. cleanup();
  384. });
  385. } // No test setup with other test runners available
  386. /* istanbul ignore else */
  387. if (typeof beforeAll === 'function' && typeof afterAll === 'function') {
  388. // This matches the behavior of React < 18.
  389. let previousIsReactActEnvironment = getIsReactActEnvironment();
  390. beforeAll(() => {
  391. previousIsReactActEnvironment = getIsReactActEnvironment();
  392. setIsReactActEnvironment(true);
  393. });
  394. afterAll(() => {
  395. setIsReactActEnvironment(previousIsReactActEnvironment);
  396. });
  397. }
  398. }
  399. export { act, cleanup, fireEvent, render, renderHook };