@mui/internal-test-utils 2.0.15 → 2.0.16

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 (212) hide show
  1. package/{src/chai.types.ts → chai.types.d.ts} +7 -40
  2. package/chai.types.js +5 -0
  3. package/chaiPlugin.d.ts +4 -0
  4. package/chaiPlugin.js +287 -0
  5. package/{build/components.d.ts → components.d.ts} +18 -19
  6. package/components.js +64 -0
  7. package/createDOM.d.ts +2 -0
  8. package/{src/createDOM.js → createDOM.js} +17 -35
  9. package/createDescribe.d.ts +7 -0
  10. package/createDescribe.js +26 -0
  11. package/createRenderer.d.ts +214 -0
  12. package/createRenderer.js +428 -0
  13. package/createRenderer.test.d.ts +1 -0
  14. package/describeConformance.d.ts +200 -0
  15. package/describeConformance.js +1038 -0
  16. package/env.d.ts +1 -0
  17. package/env.js +11 -0
  18. package/esm/chai.types.d.ts +74 -0
  19. package/esm/chai.types.js +3 -0
  20. package/esm/chaiPlugin.d.ts +4 -0
  21. package/esm/chaiPlugin.js +281 -0
  22. package/esm/components.d.ts +35 -0
  23. package/esm/components.js +56 -0
  24. package/esm/createDOM.d.ts +2 -0
  25. package/esm/createDOM.js +47 -0
  26. package/esm/createDescribe.d.ts +7 -0
  27. package/esm/createDescribe.js +19 -0
  28. package/esm/createRenderer.d.ts +214 -0
  29. package/esm/createRenderer.js +390 -0
  30. package/esm/createRenderer.test.d.ts +1 -0
  31. package/esm/describeConformance.d.ts +200 -0
  32. package/esm/describeConformance.js +1024 -0
  33. package/esm/env.d.ts +1 -0
  34. package/esm/env.js +5 -0
  35. package/{build → esm}/fireDiscreteEvent.d.ts +1 -2
  36. package/{src/fireDiscreteEvent.ts → esm/fireDiscreteEvent.js} +10 -18
  37. package/esm/flushMicrotasks.d.ts +1 -0
  38. package/{src/flushMicrotasks.ts → esm/flushMicrotasks.js} +2 -3
  39. package/{build → esm}/focusVisible.d.ts +1 -2
  40. package/{src/focusVisible.ts → esm/focusVisible.js} +10 -9
  41. package/esm/index.d.ts +18 -0
  42. package/esm/index.js +27 -0
  43. package/esm/init.d.ts +1 -0
  44. package/{src → esm}/init.js +4 -2
  45. package/esm/initMatchers.d.ts +1 -0
  46. package/esm/initMatchers.js +6 -0
  47. package/esm/initMatchers.test.d.ts +1 -0
  48. package/esm/initPlaywrightMatchers.d.ts +24 -0
  49. package/esm/initPlaywrightMatchers.js +40 -0
  50. package/esm/package.json +1 -0
  51. package/esm/reactMajor.d.ts +2 -0
  52. package/esm/reactMajor.js +2 -0
  53. package/esm/setup.d.ts +1 -0
  54. package/{src → esm}/setup.js +2 -4
  55. package/esm/setupVitest.d.ts +1 -0
  56. package/esm/setupVitest.js +28 -0
  57. package/esm/setupVitestBrowser.d.ts +1 -0
  58. package/esm/setupVitestBrowser.js +30 -0
  59. package/fireDiscreteEvent.d.ts +6 -0
  60. package/fireDiscreteEvent.js +79 -0
  61. package/flushMicrotasks.d.ts +1 -0
  62. package/flushMicrotasks.js +10 -0
  63. package/focusVisible.d.ts +7 -0
  64. package/focusVisible.js +44 -0
  65. package/index.d.ts +18 -0
  66. package/index.js +139 -0
  67. package/init.d.ts +1 -0
  68. package/init.js +15 -0
  69. package/initMatchers.d.ts +1 -0
  70. package/initMatchers.js +10 -0
  71. package/initMatchers.test.d.ts +1 -0
  72. package/initPlaywrightMatchers.d.ts +24 -0
  73. package/initPlaywrightMatchers.js +42 -0
  74. package/package.json +89 -46
  75. package/reactMajor.d.ts +2 -0
  76. package/reactMajor.js +9 -0
  77. package/setup.d.ts +1 -0
  78. package/setup.js +10 -0
  79. package/setupVitest.d.ts +1 -0
  80. package/setupVitest.js +32 -0
  81. package/setupVitestBrowser.d.ts +1 -0
  82. package/setupVitestBrowser.js +34 -0
  83. package/build/.tsbuildinfo +0 -1
  84. package/build/KarmaReporterReactProfiler.d.ts +0 -51
  85. package/build/KarmaReporterReactProfiler.d.ts.map +0 -1
  86. package/build/KarmaReporterReactProfiler.js +0 -66
  87. package/build/KarmaReporterReactProfiler.js.map +0 -1
  88. package/build/chai.types.d.ts +0 -75
  89. package/build/chai.types.d.ts.map +0 -1
  90. package/build/chai.types.js +0 -3
  91. package/build/chai.types.js.map +0 -1
  92. package/build/chaiPlugin.d.ts +0 -5
  93. package/build/chaiPlugin.d.ts.map +0 -1
  94. package/build/chaiPlugin.js +0 -416
  95. package/build/chaiPlugin.js.map +0 -1
  96. package/build/components.d.ts.map +0 -1
  97. package/build/components.js +0 -88
  98. package/build/components.js.map +0 -1
  99. package/build/createDOM.d.ts +0 -3
  100. package/build/createDOM.d.ts.map +0 -1
  101. package/build/createDOM.js +0 -60
  102. package/build/createDOM.js.map +0 -1
  103. package/build/createDescribe.d.ts +0 -8
  104. package/build/createDescribe.d.ts.map +0 -1
  105. package/build/createDescribe.js +0 -22
  106. package/build/createDescribe.js.map +0 -1
  107. package/build/createRenderer.d.ts +0 -215
  108. package/build/createRenderer.d.ts.map +0 -1
  109. package/build/createRenderer.js +0 -564
  110. package/build/createRenderer.js.map +0 -1
  111. package/build/createRenderer.test.d.ts +0 -2
  112. package/build/createRenderer.test.d.ts.map +0 -1
  113. package/build/createRenderer.test.js +0 -58
  114. package/build/createRenderer.test.js.map +0 -1
  115. package/build/describeConformance.d.ts +0 -201
  116. package/build/describeConformance.d.ts.map +0 -1
  117. package/build/describeConformance.js +0 -859
  118. package/build/describeConformance.js.map +0 -1
  119. package/build/describeSkipIf.d.ts +0 -4
  120. package/build/describeSkipIf.d.ts.map +0 -1
  121. package/build/describeSkipIf.js +0 -10
  122. package/build/describeSkipIf.js.map +0 -1
  123. package/build/fireDiscreteEvent.d.ts.map +0 -1
  124. package/build/fireDiscreteEvent.js +0 -77
  125. package/build/fireDiscreteEvent.js.map +0 -1
  126. package/build/flushMicrotasks.d.ts +0 -2
  127. package/build/flushMicrotasks.d.ts.map +0 -1
  128. package/build/flushMicrotasks.js +0 -8
  129. package/build/flushMicrotasks.js.map +0 -1
  130. package/build/focusVisible.d.ts.map +0 -1
  131. package/build/focusVisible.js +0 -38
  132. package/build/focusVisible.js.map +0 -1
  133. package/build/index.d.ts +0 -18
  134. package/build/index.d.ts.map +0 -1
  135. package/build/index.js +0 -68
  136. package/build/index.js.map +0 -1
  137. package/build/init.d.ts +0 -2
  138. package/build/init.d.ts.map +0 -1
  139. package/build/init.js +0 -46
  140. package/build/init.js.map +0 -1
  141. package/build/initMatchers.d.ts +0 -2
  142. package/build/initMatchers.d.ts.map +0 -1
  143. package/build/initMatchers.js +0 -45
  144. package/build/initMatchers.js.map +0 -1
  145. package/build/initMatchers.test.d.ts +0 -2
  146. package/build/initMatchers.test.d.ts.map +0 -1
  147. package/build/initMatchers.test.js +0 -101
  148. package/build/initMatchers.test.js.map +0 -1
  149. package/build/initPlaywrightMatchers.d.ts +0 -25
  150. package/build/initPlaywrightMatchers.d.ts.map +0 -1
  151. package/build/initPlaywrightMatchers.js +0 -73
  152. package/build/initPlaywrightMatchers.js.map +0 -1
  153. package/build/mochaHooks.d.ts +0 -24
  154. package/build/mochaHooks.d.ts.map +0 -1
  155. package/build/mochaHooks.js +0 -165
  156. package/build/mochaHooks.js.map +0 -1
  157. package/build/mochaHooks.test.d.ts +0 -2
  158. package/build/mochaHooks.test.d.ts.map +0 -1
  159. package/build/mochaHooks.test.js +0 -128
  160. package/build/mochaHooks.test.js.map +0 -1
  161. package/build/reactMajor.d.ts +0 -3
  162. package/build/reactMajor.d.ts.map +0 -1
  163. package/build/reactMajor.js +0 -38
  164. package/build/reactMajor.js.map +0 -1
  165. package/build/setup.d.ts +0 -2
  166. package/build/setup.d.ts.map +0 -1
  167. package/build/setup.js +0 -10
  168. package/build/setup.js.map +0 -1
  169. package/build/setupBabel.d.ts +0 -2
  170. package/build/setupBabel.d.ts.map +0 -1
  171. package/build/setupBabel.js +0 -5
  172. package/build/setupBabel.js.map +0 -1
  173. package/build/setupBabelPlaywright.d.ts +0 -2
  174. package/build/setupBabelPlaywright.d.ts.map +0 -1
  175. package/build/setupBabelPlaywright.js +0 -14
  176. package/build/setupBabelPlaywright.js.map +0 -1
  177. package/build/setupJSDOM.d.ts +0 -7
  178. package/build/setupJSDOM.d.ts.map +0 -1
  179. package/build/setupJSDOM.js +0 -17
  180. package/build/setupJSDOM.js.map +0 -1
  181. package/build/setupKarma.d.ts +0 -2
  182. package/build/setupKarma.d.ts.map +0 -1
  183. package/build/setupKarma.js +0 -56
  184. package/build/setupKarma.js.map +0 -1
  185. package/build/setupVitest.d.ts +0 -2
  186. package/build/setupVitest.d.ts.map +0 -1
  187. package/build/setupVitest.js +0 -131
  188. package/build/setupVitest.js.map +0 -1
  189. package/src/KarmaReporterReactProfiler.js +0 -82
  190. package/src/chai-augmentation.d.ts +0 -8
  191. package/src/chaiPlugin.ts +0 -515
  192. package/src/components.tsx +0 -61
  193. package/src/createDOM.d.ts +0 -9
  194. package/src/createDescribe.ts +0 -31
  195. package/src/createRenderer.test.js +0 -31
  196. package/src/createRenderer.tsx +0 -808
  197. package/src/describeConformance.tsx +0 -1257
  198. package/src/describeSkipIf.tsx +0 -11
  199. package/src/index.ts +0 -25
  200. package/src/initMatchers.test.js +0 -124
  201. package/src/initMatchers.ts +0 -7
  202. package/src/initPlaywrightMatchers.ts +0 -101
  203. package/src/mochaHooks.js +0 -200
  204. package/src/mochaHooks.test.js +0 -116
  205. package/src/reactMajor.ts +0 -3
  206. package/src/setupBabel.js +0 -3
  207. package/src/setupBabelPlaywright.js +0 -13
  208. package/src/setupJSDOM.js +0 -20
  209. package/src/setupKarma.js +0 -65
  210. package/src/setupVitest.ts +0 -117
  211. package/tsconfig.build.json +0 -16
  212. package/tsconfig.json +0 -17
package/env.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function isJsdom(): boolean;
package/env.js ADDED
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.isJsdom = isJsdom;
7
+ /* eslint-disable import/prefer-default-export */
8
+
9
+ function isJsdom() {
10
+ return window.navigator.userAgent.includes('jsdom');
11
+ }
@@ -0,0 +1,74 @@
1
+ export {};
2
+ declare global {
3
+ namespace Chai {
4
+ interface Assertion {
5
+ /**
6
+ * Checks `expectedStyle` is a subset of the elements inline style i.e. `element.style`.
7
+ * @example expect(element).toHaveInlineStyle({ width: '200px' })
8
+ */
9
+ toHaveInlineStyle(expectedStyle: Partial<Record<Exclude<keyof CSSStyleDeclaration, 'getPropertyPriority' | 'getPropertyValue' | 'item' | 'removeProperty' | 'setProperty' | number>, string>>): void;
10
+ /**
11
+ * Checks `expectedStyle` is a subset of the elements computed style i.e. `window.getComputedStyle(element)`.
12
+ * @example expect(element).toHaveComputedStyle({ width: '200px' })
13
+ */
14
+ toHaveComputedStyle(expectedStyle: Partial<Record<Exclude<keyof CSSStyleDeclaration, 'getPropertyPriority' | 'getPropertyValue' | 'item' | 'removeProperty' | 'setProperty' | number>, string>>): void;
15
+ /**
16
+ * Check if an element's [`visibility`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/visibility) is not `hidden` or `collapsed`.
17
+ */
18
+ toBeVisible(): void;
19
+ /**
20
+ * Check if an element's [`visibility`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/visibility) is `hidden` or `collapsed`.
21
+ */
22
+ toBeHidden(): void;
23
+ /**
24
+ * Checks if the element is inaccessible.
25
+ *
26
+ * Elements are considered inaccessible if they either:
27
+ * - have [`visibility`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/visibility) `hidden`
28
+ * - have [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/display) `none`
29
+ * - have `aria-hidden` `true` or any of their parents
30
+ *
31
+ * @see [Excluding Elements from the Accessibility Tree](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion)
32
+ */
33
+ toBeInaccessible(): void;
34
+ toHaveAccessibleDescription(description: string): void;
35
+ /**
36
+ * Checks if the accessible name computation (according to `accname` spec)
37
+ * matches the expectation.
38
+ *
39
+ * @see https://www.w3.org/TR/accname-1.2/
40
+ * @param name
41
+ */
42
+ toHaveAccessibleName(name: string): void;
43
+ /**
44
+ * Checks if the element is actually focused i.e. `document.activeElement` is equal to the actual element.
45
+ */
46
+ toHaveFocus(): void;
47
+ /**
48
+ * Checks if the element is the active-descendant of the active element.
49
+ */
50
+ toHaveVirtualFocus(): void;
51
+ /**
52
+ * Matches calls to `console.warn` in the asserted callback.
53
+ *
54
+ * @example expect(() => render()).not.toWarnDev()
55
+ * @example expect(() => render()).toWarnDev('single message')
56
+ * @example expect(() => render()).toWarnDev(['first warning', 'then the second'])
57
+ */
58
+ toWarnDev(messages?: string | readonly (string | boolean)[]): void;
59
+ /**
60
+ * Matches calls to `console.error` in the asserted callback.
61
+ *
62
+ * @example expect(() => render()).not.toErrorDev()
63
+ * @example expect(() => render()).toErrorDev('single message')
64
+ * @example expect(() => render()).toErrorDev(['first warning', 'then the second'])
65
+ */
66
+ toErrorDev(messages?: string | readonly (string | boolean)[]): void;
67
+ /**
68
+ * Asserts that the given callback throws an error matching the given message in development (process.env.NODE_ENV !== 'production').
69
+ * In production it expects a minified error.
70
+ */
71
+ toThrowMinified(message: string | RegExp): void;
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,3 @@
1
+ export {};
2
+
3
+ // https://stackoverflow.com/a/46755166/3406963
@@ -0,0 +1,4 @@
1
+ import * as chai from 'chai';
2
+ import "./chai.types.js";
3
+ declare const chaiPlugin: Parameters<typeof chai.use>[0];
4
+ export default chaiPlugin;
@@ -0,0 +1,281 @@
1
+ import { isInaccessible } from '@testing-library/dom';
2
+ import { prettyDOM } from '@testing-library/react/pure';
3
+ import { computeAccessibleDescription, computeAccessibleName } from 'dom-accessibility-api';
4
+ import formatUtil from 'format-util';
5
+ import { kebabCase } from 'es-toolkit/string';
6
+ import { AssertionError } from 'assertion-error';
7
+ import "./chai.types.js";
8
+ import { isJsdom } from "./env.js";
9
+
10
+ // chai#utils.elToString that looks like stringified elements in testing-library
11
+ function elementToString(element) {
12
+ if (typeof element?.nodeType === 'number') {
13
+ return prettyDOM(element, undefined, {
14
+ highlight: true,
15
+ maxDepth: 1
16
+ });
17
+ }
18
+ return String(element);
19
+ }
20
+ const chaiPlugin = (chaiAPI, utils) => {
21
+ const blockElements = new Set(['html', 'address', 'blockquote', 'body', 'dd', 'div', 'dl', 'dt', 'fieldset', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'noframes', 'ol', 'p', 'ul', 'center', 'dir', 'hr', 'menu', 'pre']);
22
+ function pretendVisibleGetComputedStyle(element) {
23
+ // `CSSStyleDeclaration` is not constructable
24
+ // https://stackoverflow.com/a/52732909/3406963
25
+ // this is not equivalent to the declaration from `getComputedStyle`
26
+ // for example `getComputedStyle` would return a readonly declaration
27
+ // let's hope this doesn't get passed around until it's no longer clear where it comes from
28
+ const declaration = document.createElement('span').style;
29
+
30
+ // initial values
31
+ declaration.content = '';
32
+ // technically it's `inline`. We partially apply the default user agent sheet (chrome) here
33
+ // we're only interested in elements that use block
34
+ declaration.display = blockElements.has(element.tagName) ? 'block' : 'inline';
35
+ declaration.visibility = 'visible';
36
+ return declaration;
37
+ }
38
+
39
+ // better diff view for expect(element).to.equal(document.activeElement)
40
+ chaiAPI.Assertion.addMethod('toHaveFocus', function elementIsFocused() {
41
+ const element = utils.flag(this, 'object');
42
+ this.assert(element === document.activeElement, `expected element to have focus`, `expected element to NOT have focus \n${elementToString(element)}`, elementToString(element), elementToString(document.activeElement));
43
+ });
44
+ chaiAPI.Assertion.addMethod('toHaveVirtualFocus', function elementIsVirtuallyFocused() {
45
+ const element = utils.flag(this, 'object');
46
+ const id = element.getAttribute('id');
47
+ const virtuallyFocusedElementId = document.activeElement.getAttribute('aria-activedescendant');
48
+ this.assert(virtuallyFocusedElementId === id, `expected element to be virtually focused\nexpected id #{exp}\n${virtuallyFocusedElementId === null ? `activeElement: ${elementToString(document.activeElement)}` : 'actual id: #{act}'}`, 'expected element to NOT to be virtually focused', id, virtuallyFocusedElementId, virtuallyFocusedElementId !== null);
49
+ });
50
+ chaiAPI.Assertion.addMethod('toBeInaccessible', function elementIsAccessible() {
51
+ const element = utils.flag(this, 'object');
52
+ const inaccessible = isInaccessible(element);
53
+ this.assert(inaccessible === true, `expected \n${elementToString(element)} to be inaccessible but it was accessible`, `expected \n${elementToString(element)} to be accessible but it was inaccessible`,
54
+ // Not interested in a diff but the typings require the 4th parameter.
55
+ undefined);
56
+ });
57
+ chaiAPI.Assertion.addMethod('toHaveAccessibleName', function hasAccessibleName(expectedName) {
58
+ const root = utils.flag(this, 'object');
59
+ // make sure it's an Element
60
+ new chaiAPI.Assertion(root.nodeType, `Expected an Element but got '${String(root)}'`).to.equal(1);
61
+ const actualName = computeAccessibleName(root, {
62
+ computedStyleSupportsPseudoElements: !isJsdom(),
63
+ // in local development we pretend to be visible. full getComputedStyle is
64
+ // expensive and reserved for CI
65
+ getComputedStyle: process.env.CI ? undefined : pretendVisibleGetComputedStyle
66
+ });
67
+ this.assert(actualName === expectedName, `expected \n${elementToString(root)} to have accessible name #{exp} but got #{act} instead.`, `expected \n${elementToString(root)} not to have accessible name #{exp}.`, expectedName, actualName);
68
+ });
69
+ chaiAPI.Assertion.addMethod('toHaveAccessibleDescription', function hasAccessibleDescription(expectedDescription) {
70
+ const root = utils.flag(this, 'object');
71
+ // make sure it's an Element
72
+ new chaiAPI.Assertion(root.nodeType, `Expected an Element but got '${String(root)}'`).to.equal(1);
73
+ const actualDescription = computeAccessibleDescription(root, {
74
+ // in local development we pretend to be visible. full getComputedStyle is
75
+ // expensive and reserved for CI
76
+ getComputedStyle: process.env.CI ? undefined : pretendVisibleGetComputedStyle
77
+ });
78
+ const possibleDescriptionComputationMessage = root.hasAttribute('title') ? ' computeAccessibleDescription can be misleading when a `title` attribute is used. This might be a bug in `dom-accessibility-api`.' : '';
79
+ this.assert(actualDescription === expectedDescription, `expected \n${elementToString(root)} to have accessible description #{exp} but got #{act} instead.${possibleDescriptionComputationMessage}`, `expected \n${elementToString(root)} not to have accessible description #{exp}.${possibleDescriptionComputationMessage}`, expectedDescription, actualDescription);
80
+ });
81
+
82
+ /**
83
+ * Correct name for `to.be.visible`
84
+ */
85
+ chaiAPI.Assertion.addMethod('toBeVisible', function toBeVisible() {
86
+ // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-unused-expressions
87
+ new chaiAPI.Assertion(this._obj).to.be.visible;
88
+ });
89
+
90
+ /**
91
+ * Correct name for `not.to.be.visible`
92
+ */
93
+ chaiAPI.Assertion.addMethod('toBeHidden', function toBeHidden() {
94
+ // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-unused-expressions
95
+ new chaiAPI.Assertion(this._obj).not.to.be.visible;
96
+ });
97
+ function assertMatchingStyles(actualStyleDeclaration, expectedStyleUnnormalized, options) {
98
+ const {
99
+ styleTypeHint
100
+ } = options;
101
+
102
+ // Compare objects using hyphen case.
103
+ // This is closer to actual CSS and required for getPropertyValue anyway.
104
+ const expectedStyle = {};
105
+ Object.keys(expectedStyleUnnormalized).forEach(cssProperty => {
106
+ const hyphenCasedPropertyName = kebabCase(cssProperty);
107
+ const isVendorPrefixed = /^(moz|ms|o|webkit)-/.test(hyphenCasedPropertyName);
108
+ const propertyName = isVendorPrefixed ? `-${hyphenCasedPropertyName}` : hyphenCasedPropertyName;
109
+ expectedStyle[propertyName] = expectedStyleUnnormalized[cssProperty];
110
+ });
111
+ const shorthandProperties = new Set(['all', 'animation', 'background', 'border', 'border-block-end', 'border-block-start', 'border-bottom', 'border-color', 'border-image', 'border-inline-end', 'border-inline-start', 'border-left', 'border-radius', 'border-right', 'border-style', 'border-top', 'border-width', 'column-rule', 'columns', 'flex', 'flex-flow', 'font', 'gap', 'grid', 'grid-area', 'grid-column', 'grid-row', 'grid-template', 'list-style', 'margin', 'mask', 'offset', 'outline', 'overflow', 'padding', 'place-content', 'place-items', 'place-self', 'scroll-margin', 'scroll-padding', 'text-decoration', 'text-emphasis', 'transition']);
112
+ const usedShorthandProperties = Object.keys(expectedStyle).filter(cssProperty => {
113
+ return shorthandProperties.has(cssProperty);
114
+ });
115
+ if (usedShorthandProperties.length > 0) {
116
+ throw new Error([`Shorthand properties are not supported in ${styleTypeHint} styles matchers since browsers can compute them differently. `, 'Use longhand properties instead for the follow shorthand properties:\n', usedShorthandProperties.map(cssProperty => {
117
+ return `- https://developer.mozilla.org/en-US/docs/Web/CSS/${cssProperty}#constituent_properties`;
118
+ }).join('\n')].join(''));
119
+ }
120
+ const actualStyle = {};
121
+ Object.keys(expectedStyle).forEach(cssProperty => {
122
+ actualStyle[cssProperty] = actualStyleDeclaration.getPropertyValue(cssProperty);
123
+ });
124
+ const jsdomHint = 'Styles in JSDOM e.g. from `test:unit` are often misleading since JSDOM does not implement the Cascade nor actual CSS property value computation. ' + "If results differ between real browsers and JSDOM, skip the test in JSDOM e.g. `it.skipIf(isJsdom())('...`";
125
+ const shorthandHint = 'Browsers can compute shorthand properties differently. Prefer longhand properties e.g. `borderTopColor`, `borderRightColor` etc. instead of `border` or `border-color`.';
126
+ const messageHint = `${jsdomHint}\n${shorthandHint}`;
127
+ this.assert(
128
+ // TODO Fix upstream docs/types
129
+ utils.eql(actualStyle, expectedStyle), `expected #{this} to have ${styleTypeHint} style #{exp} \n\n${messageHint}`, `expected #{this} not to have ${styleTypeHint} style #{exp}${messageHint}`, expectedStyle, actualStyle, true);
130
+ }
131
+ chaiAPI.Assertion.addMethod('toHaveInlineStyle', function toHaveInlineStyle(expectedStyleUnnormalized) {
132
+ const element = utils.flag(this, 'object');
133
+ if (element?.nodeType !== 1) {
134
+ // Same pre-condition for negated and unnegated assertion
135
+ throw new AssertionError(`Expected an Element but got ${String(element)}`);
136
+ }
137
+ assertMatchingStyles.call(this, element.style, expectedStyleUnnormalized, {
138
+ styleTypeHint: 'inline'
139
+ });
140
+ });
141
+ chaiAPI.Assertion.addMethod('toHaveComputedStyle', function toHaveComputedStyle(expectedStyleUnnormalized) {
142
+ const element = utils.flag(this, 'object');
143
+ if (element?.nodeType !== 1) {
144
+ // Same pre-condition for negated and unnegated assertion
145
+ throw new AssertionError(`Expected an Element but got ${String(element)}`);
146
+ }
147
+ const computedStyle = element.ownerDocument.defaultView.getComputedStyle(element);
148
+ assertMatchingStyles.call(this, computedStyle, expectedStyleUnnormalized, {
149
+ styleTypeHint: 'computed'
150
+ });
151
+ });
152
+ chaiAPI.Assertion.addMethod('toThrowMinified', function toThrowMinified(expectedDevMessage) {
153
+ // TODO: Investigate if `as any` can be removed after https://github.com/DefinitelyTyped/DefinitelyTyped/issues/48634 is resolved.
154
+ if (process.env.NODE_ENV !== 'production') {
155
+ this.to.throw(expectedDevMessage);
156
+ } else {
157
+ utils.flag(this, 'message', "Looks like the error was not minified. This can happen if the error code hasn't been generated yet. Run `pnpm extract-error-codes` and try again.");
158
+ // TODO: Investigate if `as any` can be removed after https://github.com/DefinitelyTyped/DefinitelyTyped/issues/48634 is resolved.
159
+ this.to.throw('Minified MUI error', 'helper');
160
+ }
161
+ });
162
+ function addConsoleMatcher(matcherName, methodName) {
163
+ /**
164
+ * @param {string[]} expectedMessages
165
+ */
166
+ function matcher(expectedMessagesInput = []) {
167
+ // documented pattern to get the actual value of the assertion
168
+ // eslint-disable-next-line no-underscore-dangle
169
+ const callback = this._obj;
170
+ if (process.env.NODE_ENV !== 'production') {
171
+ const expectedMessages = typeof expectedMessagesInput === 'string' ? [expectedMessagesInput] : expectedMessagesInput.slice();
172
+ const unexpectedMessages = [];
173
+ // TODO Remove type once MUI X enables noImplicitAny
174
+ let caughtError = null;
175
+ this.assert(expectedMessages.length > 0, `Expected to call console.${methodName} but didn't provide messages. ` + `If you don't expect any messages prefer \`expect().not.${matcherName}();\`.`, `Expected no call to console.${methodName} while also expecting messages.` + 'Expected no call to console.error but provided messages. ' + "If you want to make sure a certain message isn't logged prefer the positive. " + 'By expecting certain messages you automatically expect that no other messages are logged',
176
+ // Not interested in a diff but the typings require the 4th parameter.
177
+ undefined);
178
+
179
+ // Ignore skipped messages in e.g. `[condition && 'foo']`
180
+ const remainingMessages = expectedMessages.filter(messageOrFalse => {
181
+ return messageOrFalse !== false;
182
+ });
183
+
184
+ // eslint-disable-next-line no-console
185
+ const originalMethod = console[methodName];
186
+ let messagesMatched = 0;
187
+ const consoleMatcher = (format, ...args) => {
188
+ // Ignore legacy root deprecation warnings
189
+ // TODO: Remove once we no longer use legacy roots.
190
+ if (format.includes('Use createRoot instead.') || format.includes('Use hydrateRoot instead.')) {
191
+ return;
192
+ }
193
+ const actualMessage = formatUtil(format, ...args);
194
+ const expectedMessage = remainingMessages.shift();
195
+ messagesMatched += 1;
196
+
197
+ // TODO Remove type once MUI X enables noImplicitAny
198
+ let message = null;
199
+ if (expectedMessage === undefined) {
200
+ message = `Expected no more error messages but got:\n"${actualMessage}"`;
201
+ } else if (!actualMessage.includes(expectedMessage)) {
202
+ message = `Expected #${messagesMatched} "${expectedMessage}" to be included in \n"${actualMessage}"`;
203
+ }
204
+ if (message !== null) {
205
+ const error = new Error(message);
206
+ const {
207
+ stack: fullStack
208
+ } = error;
209
+ const fullStacktrace = fullStack.replace(`Error: ${message}\n`, '').split('\n');
210
+ const usefulStacktrace = fullStacktrace
211
+ //
212
+ // first line points to this frame which is irrelevant for the tester
213
+ .slice(1);
214
+ const usefulStack = `${message}\n${usefulStacktrace.join('\n')}`;
215
+ error.stack = usefulStack;
216
+ unexpectedMessages.push(error);
217
+ }
218
+ };
219
+ // eslint-disable-next-line no-console
220
+ console[methodName] = consoleMatcher;
221
+ try {
222
+ callback();
223
+ } catch (error) {
224
+ caughtError = error;
225
+ } finally {
226
+ // eslint-disable-next-line no-console
227
+ console[methodName] = originalMethod;
228
+
229
+ // unexpected thrown error takes precedence over unexpected console call
230
+ if (caughtError !== null) {
231
+ // not the same pattern as described in the block because we don't rethrow in the catch
232
+ // eslint-disable-next-line no-unsafe-finally
233
+ throw caughtError;
234
+ }
235
+ const formatMessages = messages => {
236
+ const formattedMessages = messages.map(message => {
237
+ if (typeof message === 'string') {
238
+ return `"${message}"`;
239
+ }
240
+ // full Error
241
+ return `${message.stack}`;
242
+ });
243
+ return `\n\n - ${formattedMessages.join('\n\n- ')}`;
244
+ };
245
+ const shouldHaveWarned = utils.flag(this, 'negate') !== true;
246
+
247
+ // unreachable from expect().not.toWarnDev(messages)
248
+ if (unexpectedMessages.length > 0) {
249
+ const unexpectedMessageRecordedMessage = `Recorded unexpected console.${methodName} calls: ${formatMessages(unexpectedMessages)}`;
250
+ // chai will duplicate the stack frames from the unexpected calls in their assertion error
251
+ // it's not ideal but the test failure is located the second to last stack frame
252
+ // and the origin of the call is the second stackframe in the stack
253
+ this.assert(
254
+ // force chai to always trigger an assertion error
255
+ !shouldHaveWarned, unexpectedMessageRecordedMessage, unexpectedMessageRecordedMessage,
256
+ // Not interested in a diff but the typings require the 4th parameter.
257
+ undefined);
258
+ }
259
+ if (shouldHaveWarned) {
260
+ this.assert(remainingMessages.length === 0, `Could not match the following console.${methodName} calls. ` + `Make sure previous actions didn't call console.${methodName} by wrapping them in expect(() => {}).not.${matcherName}(): ${formatMessages(remainingMessages)}`, `Impossible state reached in \`expect().${matcherName}()\`. ` + `This is a bug in the matcher.`,
261
+ // Not interested in a diff but the typings require the 4th parameter.
262
+ undefined);
263
+ }
264
+ }
265
+ } else {
266
+ // nothing to do in prod
267
+ // If there are still console calls than our test setup throws.
268
+ callback();
269
+ }
270
+ }
271
+ chaiAPI.Assertion.addMethod(matcherName, matcher);
272
+ }
273
+
274
+ /**
275
+ * @example expect(() => render()).toWarnDev('single message')
276
+ * @example expect(() => render()).toWarnDev(['first warning', 'then the second'])
277
+ */
278
+ addConsoleMatcher('toWarnDev', 'warn');
279
+ addConsoleMatcher('toErrorDev', 'error');
280
+ };
281
+ export default chaiPlugin;
@@ -0,0 +1,35 @@
1
+ import * as React from 'react';
2
+ import PropTypes from 'prop-types';
3
+ /**
4
+ * A basic error boundary that can be used to assert thrown errors in render.
5
+ * @example <ErrorBoundary ref={errorRef}><MyComponent /></ErrorBoundary>;
6
+ * expect(errorRef.current.errors).to.have.length(0);
7
+ */
8
+ export declare class ErrorBoundary extends React.Component<{
9
+ children: React.ReactNode;
10
+ }> {
11
+ static propTypes: {
12
+ children: PropTypes.Validator<NonNullable<PropTypes.ReactNodeLike>>;
13
+ };
14
+ state: {
15
+ error: null;
16
+ };
17
+ /**
18
+ * @public
19
+ */
20
+ errors: unknown[];
21
+ static getDerivedStateFromError(error: unknown): {
22
+ error: unknown;
23
+ };
24
+ componentDidCatch(error: unknown): void;
25
+ render(): React.ReactNode;
26
+ }
27
+ /**
28
+ * Allows counting how many times the owner of `RenderCounter` rendered or
29
+ * a component within the RenderCounter tree "commits" an update.
30
+ * @example <RenderCounter ref={getRenderCountRef}>...</RenderCounter>
31
+ * getRenderCountRef.current() === 2
32
+ */
33
+ export declare const RenderCounter: React.ForwardRefExoticComponent<{
34
+ children: React.ReactNode;
35
+ } & React.RefAttributes<() => number>>;
@@ -0,0 +1,56 @@
1
+ import * as React from 'react';
2
+ import PropTypes from 'prop-types';
3
+
4
+ /**
5
+ * A basic error boundary that can be used to assert thrown errors in render.
6
+ * @example <ErrorBoundary ref={errorRef}><MyComponent /></ErrorBoundary>;
7
+ * expect(errorRef.current.errors).to.have.length(0);
8
+ */
9
+ import { jsx as _jsx } from "react/jsx-runtime";
10
+ export class ErrorBoundary extends React.Component {
11
+ state = {
12
+ error: null
13
+ };
14
+
15
+ /**
16
+ * @public
17
+ */
18
+ errors = [];
19
+ static getDerivedStateFromError(error) {
20
+ return {
21
+ error
22
+ };
23
+ }
24
+ componentDidCatch(error) {
25
+ this.errors.push(error);
26
+ }
27
+ render() {
28
+ if (this.state.error) {
29
+ return null;
30
+ }
31
+ return this.props.children;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Allows counting how many times the owner of `RenderCounter` rendered or
37
+ * a component within the RenderCounter tree "commits" an update.
38
+ * @example <RenderCounter ref={getRenderCountRef}>...</RenderCounter>
39
+ * getRenderCountRef.current() === 2
40
+ */
41
+ process.env.NODE_ENV !== "production" ? ErrorBoundary.propTypes = {
42
+ children: PropTypes.node.isRequired
43
+ } : void 0;
44
+ export const RenderCounter = /*#__PURE__*/React.forwardRef(function RenderCounter({
45
+ children
46
+ }, ref) {
47
+ const getRenderCountRef = React.useRef(0);
48
+ React.useImperativeHandle(ref, () => () => getRenderCountRef.current);
49
+ return /*#__PURE__*/_jsx(React.Profiler, {
50
+ id: "render-counter",
51
+ onRender: () => {
52
+ getRenderCountRef.current += 1;
53
+ },
54
+ children: children
55
+ });
56
+ });
@@ -0,0 +1,2 @@
1
+ export = createDOM;
2
+ declare function createDOM(): void;
@@ -0,0 +1,47 @@
1
+ const {
2
+ JSDOM
3
+ } = require('jsdom');
4
+
5
+ // We can use jsdom-global at some point if maintaining these lists is a burden.
6
+ const whitelist = [
7
+ // used by React's experimental cache API
8
+ // Always including it to reduce churn when switching between React builds
9
+ 'AbortController',
10
+ // required for fake getComputedStyle
11
+ 'CSSStyleDeclaration', 'Element', 'Event', 'TouchEvent', 'Image', 'HTMLElement', 'HTMLInputElement', 'Node', 'Performance', 'document', 'DocumentFragment'];
12
+ const blacklist = ['sessionStorage', 'localStorage'];
13
+ function createDOM() {
14
+ const dom = new JSDOM('', {
15
+ pretendToBeVisual: true,
16
+ url: 'http://localhost'
17
+ });
18
+ globalThis.window = dom.window;
19
+ // Not yet supported: https://github.com/jsdom/jsdom/issues/2152
20
+ class Touch {
21
+ constructor(instance) {
22
+ this.instance = instance;
23
+ }
24
+ get identifier() {
25
+ return this.instance.identifier;
26
+ }
27
+ get pageX() {
28
+ return this.instance.pageX;
29
+ }
30
+ get pageY() {
31
+ return this.instance.pageY;
32
+ }
33
+ get clientX() {
34
+ return this.instance.clientX;
35
+ }
36
+ get clientY() {
37
+ return this.instance.clientY;
38
+ }
39
+ }
40
+ globalThis.window.Touch = Touch;
41
+ Object.keys(dom.window).filter(key => !blacklist.includes(key)).concat(whitelist).forEach(key => {
42
+ if (typeof globalThis[key] === 'undefined') {
43
+ globalThis[key] = dom.window[key];
44
+ }
45
+ });
46
+ }
47
+ module.exports = createDOM;
@@ -0,0 +1,7 @@
1
+ type MUIDescribe<P extends any[]> = {
2
+ (...args: P): void;
3
+ skip: (...args: P) => void;
4
+ only: (...args: P) => void;
5
+ };
6
+ declare const _default: <P extends any[]>(message: string, callback: (...args: P) => void) => MUIDescribe<P>;
7
+ export default _default;
@@ -0,0 +1,19 @@
1
+ import { describe } from 'vitest';
2
+ export default (message, callback) => {
3
+ const muiDescribe = (...args) => {
4
+ describe(message, () => {
5
+ callback(...args);
6
+ });
7
+ };
8
+ muiDescribe.skip = (...args) => {
9
+ describe.skip(message, () => {
10
+ callback(...args);
11
+ });
12
+ };
13
+ muiDescribe.only = (...args) => {
14
+ describe.only(message, () => {
15
+ callback(...args);
16
+ });
17
+ };
18
+ return muiDescribe;
19
+ };