@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/src/chaiPlugin.ts DELETED
@@ -1,515 +0,0 @@
1
- import { isInaccessible } from '@testing-library/dom';
2
- import { prettyDOM } from '@testing-library/react/pure';
3
- import * as chai from 'chai';
4
- import { computeAccessibleDescription, computeAccessibleName } from 'dom-accessibility-api';
5
- import formatUtil from 'format-util';
6
- import { kebabCase } from 'es-toolkit/string';
7
- import './chai.types';
8
-
9
- const isKarma = Boolean(process.env.KARMA);
10
-
11
- function isInJSDOM() {
12
- return window.navigator.userAgent.includes('jsdom');
13
- }
14
-
15
- // chai#utils.elToString that looks like stringified elements in testing-library
16
- function elementToString(element: Element | null | undefined) {
17
- if (typeof element?.nodeType === 'number') {
18
- return prettyDOM(element, undefined, { highlight: !isKarma, maxDepth: 1 });
19
- }
20
- return String(element);
21
- }
22
-
23
- const chaiPlugin: Parameters<typeof chai.use>[0] = (chaiAPI, utils) => {
24
- const blockElements = new Set([
25
- 'html',
26
- 'address',
27
- 'blockquote',
28
- 'body',
29
- 'dd',
30
- 'div',
31
- 'dl',
32
- 'dt',
33
- 'fieldset',
34
- 'form',
35
- 'frame',
36
- 'frameset',
37
- 'h1',
38
- 'h2',
39
- 'h3',
40
- 'h4',
41
- 'h5',
42
- 'h6',
43
- 'noframes',
44
- 'ol',
45
- 'p',
46
- 'ul',
47
- 'center',
48
- 'dir',
49
- 'hr',
50
- 'menu',
51
- 'pre',
52
- ]);
53
-
54
- function pretendVisibleGetComputedStyle(element: Element): CSSStyleDeclaration {
55
- // `CSSStyleDeclaration` is not constructable
56
- // https://stackoverflow.com/a/52732909/3406963
57
- // this is not equivalent to the declaration from `getComputedStyle`
58
- // for example `getComputedStyle` would return a readonly declaration
59
- // let's hope this doesn't get passed around until it's no longer clear where it comes from
60
- const declaration = document.createElement('span').style;
61
-
62
- // initial values
63
- declaration.content = '';
64
- // technically it's `inline`. We partially apply the default user agent sheet (chrome) here
65
- // we're only interested in elements that use block
66
- declaration.display = blockElements.has(element.tagName) ? 'block' : 'inline';
67
- declaration.visibility = 'visible';
68
-
69
- return declaration;
70
- }
71
-
72
- // better diff view for expect(element).to.equal(document.activeElement)
73
- chaiAPI.Assertion.addMethod('toHaveFocus', function elementIsFocused() {
74
- const element = utils.flag(this, 'object');
75
-
76
- this.assert(
77
- element === document.activeElement,
78
- // karma does not show the diff like mocha does
79
- `expected element to have focus${isKarma ? '\nexpected #{exp}\nactual: #{act}' : ''}`,
80
- `expected element to NOT have focus \n${elementToString(element)}`,
81
- elementToString(element),
82
- elementToString(document.activeElement),
83
- );
84
- });
85
-
86
- chaiAPI.Assertion.addMethod('toHaveVirtualFocus', function elementIsVirtuallyFocused() {
87
- const element = utils.flag(this, 'object');
88
- const id = element.getAttribute('id');
89
-
90
- const virtuallyFocusedElementId = document.activeElement!.getAttribute('aria-activedescendant');
91
-
92
- this.assert(
93
- virtuallyFocusedElementId === id,
94
- `expected element to be virtually focused\nexpected id #{exp}\n${
95
- virtuallyFocusedElementId === null
96
- ? `activeElement: ${elementToString(document.activeElement)}`
97
- : 'actual id: #{act}'
98
- }`,
99
- 'expected element to NOT to be virtually focused',
100
- id,
101
- virtuallyFocusedElementId,
102
- virtuallyFocusedElementId !== null,
103
- );
104
- });
105
-
106
- chaiAPI.Assertion.addMethod('toBeInaccessible', function elementIsAccessible() {
107
- const element = utils.flag(this, 'object');
108
-
109
- const inaccessible = isInaccessible(element);
110
-
111
- this.assert(
112
- inaccessible === true,
113
- `expected \n${elementToString(element)} to be inaccessible but it was accessible`,
114
- `expected \n${elementToString(element)} to be accessible but it was inaccessible`,
115
- // Not interested in a diff but the typings require the 4th parameter.
116
- undefined,
117
- );
118
- });
119
-
120
- chaiAPI.Assertion.addMethod('toHaveAccessibleName', function hasAccessibleName(expectedName) {
121
- const root = utils.flag(this, 'object');
122
- // make sure it's an Element
123
- new chaiAPI.Assertion(root.nodeType, `Expected an Element but got '${String(root)}'`).to.equal(
124
- 1,
125
- );
126
-
127
- const actualName = computeAccessibleName(root, {
128
- computedStyleSupportsPseudoElements: !isInJSDOM(),
129
- // in local development we pretend to be visible. full getComputedStyle is
130
- // expensive and reserved for CI
131
- getComputedStyle: process.env.CI ? undefined : pretendVisibleGetComputedStyle,
132
- });
133
-
134
- this.assert(
135
- actualName === expectedName,
136
- `expected \n${elementToString(root)} to have accessible name #{exp} but got #{act} instead.`,
137
- `expected \n${elementToString(root)} not to have accessible name #{exp}.`,
138
- expectedName,
139
- actualName,
140
- );
141
- });
142
-
143
- chaiAPI.Assertion.addMethod(
144
- 'toHaveAccessibleDescription',
145
- function hasAccessibleDescription(expectedDescription) {
146
- const root = utils.flag(this, 'object');
147
- // make sure it's an Element
148
- new chaiAPI.Assertion(
149
- root.nodeType,
150
- `Expected an Element but got '${String(root)}'`,
151
- ).to.equal(1);
152
-
153
- const actualDescription = computeAccessibleDescription(root, {
154
- // in local development we pretend to be visible. full getComputedStyle is
155
- // expensive and reserved for CI
156
- getComputedStyle: process.env.CI ? undefined : pretendVisibleGetComputedStyle,
157
- });
158
-
159
- const possibleDescriptionComputationMessage = root.hasAttribute('title')
160
- ? ' computeAccessibleDescription can be misleading when a `title` attribute is used. This might be a bug in `dom-accessibility-api`.'
161
- : '';
162
- this.assert(
163
- actualDescription === expectedDescription,
164
- `expected \n${elementToString(
165
- root,
166
- )} to have accessible description #{exp} but got #{act} instead.${possibleDescriptionComputationMessage}`,
167
- `expected \n${elementToString(
168
- root,
169
- )} not to have accessible description #{exp}.${possibleDescriptionComputationMessage}`,
170
- expectedDescription,
171
- actualDescription,
172
- );
173
- },
174
- );
175
-
176
- /**
177
- * Correct name for `to.be.visible`
178
- */
179
- chaiAPI.Assertion.addMethod('toBeVisible', function toBeVisible() {
180
- // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-unused-expressions
181
- new chaiAPI.Assertion(this._obj).to.be.visible;
182
- });
183
-
184
- /**
185
- * Correct name for `not.to.be.visible`
186
- */
187
- chaiAPI.Assertion.addMethod('toBeHidden', function toBeHidden() {
188
- // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-unused-expressions
189
- new chaiAPI.Assertion(this._obj).not.to.be.visible;
190
- });
191
-
192
- function assertMatchingStyles(
193
- this: Chai.AssertionStatic,
194
- actualStyleDeclaration: CSSStyleDeclaration,
195
- expectedStyleUnnormalized: Record<string, string>,
196
- options: { styleTypeHint: string },
197
- ): void {
198
- const { styleTypeHint } = options;
199
-
200
- // Compare objects using hyphen case.
201
- // This is closer to actual CSS and required for getPropertyValue anyway.
202
- const expectedStyle: Record<string, string> = {};
203
- Object.keys(expectedStyleUnnormalized).forEach((cssProperty) => {
204
- const hyphenCasedPropertyName = kebabCase(cssProperty);
205
- const isVendorPrefixed = /^(moz|ms|o|webkit)-/.test(hyphenCasedPropertyName);
206
- const propertyName = isVendorPrefixed
207
- ? `-${hyphenCasedPropertyName}`
208
- : hyphenCasedPropertyName;
209
- expectedStyle[propertyName] = expectedStyleUnnormalized[cssProperty];
210
- });
211
-
212
- const shorthandProperties = new Set([
213
- 'all',
214
- 'animation',
215
- 'background',
216
- 'border',
217
- 'border-block-end',
218
- 'border-block-start',
219
- 'border-bottom',
220
- 'border-color',
221
- 'border-image',
222
- 'border-inline-end',
223
- 'border-inline-start',
224
- 'border-left',
225
- 'border-radius',
226
- 'border-right',
227
- 'border-style',
228
- 'border-top',
229
- 'border-width',
230
- 'column-rule',
231
- 'columns',
232
- 'flex',
233
- 'flex-flow',
234
- 'font',
235
- 'gap',
236
- 'grid',
237
- 'grid-area',
238
- 'grid-column',
239
- 'grid-row',
240
- 'grid-template',
241
- 'list-style',
242
- 'margin',
243
- 'mask',
244
- 'offset',
245
- 'outline',
246
- 'overflow',
247
- 'padding',
248
- 'place-content',
249
- 'place-items',
250
- 'place-self',
251
- 'scroll-margin',
252
- 'scroll-padding',
253
- 'text-decoration',
254
- 'text-emphasis',
255
- 'transition',
256
- ]);
257
- const usedShorthandProperties = Object.keys(expectedStyle).filter((cssProperty) => {
258
- return shorthandProperties.has(cssProperty);
259
- });
260
- if (usedShorthandProperties.length > 0) {
261
- throw new Error(
262
- [
263
- `Shorthand properties are not supported in ${styleTypeHint} styles matchers since browsers can compute them differently. `,
264
- 'Use longhand properties instead for the follow shorthand properties:\n',
265
- usedShorthandProperties
266
- .map((cssProperty) => {
267
- return `- https://developer.mozilla.org/en-US/docs/Web/CSS/${cssProperty}#constituent_properties`;
268
- })
269
- .join('\n'),
270
- ].join(''),
271
- );
272
- }
273
-
274
- const actualStyle: Record<string, string> = {};
275
- Object.keys(expectedStyle).forEach((cssProperty) => {
276
- actualStyle[cssProperty] = actualStyleDeclaration.getPropertyValue(cssProperty);
277
- });
278
-
279
- const jsdomHint =
280
- 'Styles in JSDOM e.g. from `test:unit` are often misleading since JSDOM does not implement the Cascade nor actual CSS property value computation. ' +
281
- 'If results differ between real browsers and JSDOM, skip the test in JSDOM e.g. `if (window.navigator.userAgent.includes("jsdom")) this.skip();`';
282
- const shorthandHint =
283
- 'Browsers can compute shorthand properties differently. Prefer longhand properties e.g. `borderTopColor`, `borderRightColor` etc. instead of `border` or `border-color`.';
284
- const messageHint = `${jsdomHint}\n${shorthandHint}`;
285
-
286
- if (isKarma) {
287
- // `#{exp}` and `#{act}` placeholders escape the newlines
288
- const expected = JSON.stringify(expectedStyle, null, 2);
289
- const actual = JSON.stringify(actualStyle, null, 2);
290
- // karma's `dots` reporter does not support diffs
291
- this.assert(
292
- // TODO Fix upstream docs/types
293
- (utils as any).eql(actualStyle, expectedStyle),
294
- `expected ${styleTypeHint} style of #{this} did not match\nExpected:\n${expected}\nActual:\n${actual}\n\n\n${messageHint}`,
295
- `expected #{this} to not have ${styleTypeHint} style\n${expected}\n\n\n${messageHint}`,
296
- expectedStyle,
297
- actualStyle,
298
- );
299
- } else {
300
- this.assert(
301
- // TODO Fix upstream docs/types
302
- (utils as any).eql(actualStyle, expectedStyle),
303
- `expected #{this} to have ${styleTypeHint} style #{exp} \n\n${messageHint}`,
304
- `expected #{this} not to have ${styleTypeHint} style #{exp}${messageHint}`,
305
- expectedStyle,
306
- actualStyle,
307
- true,
308
- );
309
- }
310
- }
311
-
312
- chaiAPI.Assertion.addMethod(
313
- 'toHaveInlineStyle',
314
- function toHaveInlineStyle(expectedStyleUnnormalized: Record<string, string>) {
315
- const element = utils.flag(this, 'object') as HTMLElement;
316
- if (element?.nodeType !== 1) {
317
- // Same pre-condition for negated and unnegated assertion
318
- throw new chai.AssertionError(`Expected an Element but got ${String(element)}`);
319
- }
320
-
321
- assertMatchingStyles.call(this, element.style, expectedStyleUnnormalized, {
322
- styleTypeHint: 'inline',
323
- });
324
- },
325
- );
326
-
327
- chaiAPI.Assertion.addMethod(
328
- 'toHaveComputedStyle',
329
- function toHaveComputedStyle(expectedStyleUnnormalized: Record<string, string>) {
330
- const element = utils.flag(this, 'object') as HTMLElement;
331
- if (element?.nodeType !== 1) {
332
- // Same pre-condition for negated and unnegated assertion
333
- throw new chai.AssertionError(`Expected an Element but got ${String(element)}`);
334
- }
335
- const computedStyle = element.ownerDocument.defaultView!.getComputedStyle(element);
336
-
337
- assertMatchingStyles.call(this, computedStyle, expectedStyleUnnormalized, {
338
- styleTypeHint: 'computed',
339
- });
340
- },
341
- );
342
-
343
- chaiAPI.Assertion.addMethod('toThrowMinified', function toThrowMinified(expectedDevMessage) {
344
- // TODO: Investigate if `as any` can be removed after https://github.com/DefinitelyTyped/DefinitelyTyped/issues/48634 is resolved.
345
- if (process.env.NODE_ENV !== 'production') {
346
- (this as any).to.throw(expectedDevMessage);
347
- } else {
348
- utils.flag(
349
- this,
350
- 'message',
351
- "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.",
352
- );
353
- // TODO: Investigate if `as any` can be removed after https://github.com/DefinitelyTyped/DefinitelyTyped/issues/48634 is resolved.
354
- (this as any).to.throw('Minified MUI error', 'helper');
355
- }
356
- });
357
-
358
- function addConsoleMatcher(matcherName: string, methodName: 'error' | 'warn') {
359
- /**
360
- * @param {string[]} expectedMessages
361
- */
362
- function matcher(this: Chai.AssertionStatic, expectedMessagesInput = []) {
363
- // documented pattern to get the actual value of the assertion
364
- // eslint-disable-next-line no-underscore-dangle
365
- const callback = this._obj;
366
-
367
- if (process.env.NODE_ENV !== 'production') {
368
- const expectedMessages =
369
- typeof expectedMessagesInput === 'string'
370
- ? [expectedMessagesInput]
371
- : expectedMessagesInput.slice();
372
- const unexpectedMessages: Error[] = [];
373
- // TODO Remove type once MUI X enables noImplicitAny
374
- let caughtError: unknown | null = null;
375
-
376
- this.assert(
377
- expectedMessages.length > 0,
378
- `Expected to call console.${methodName} but didn't provide messages. ` +
379
- `If you don't expect any messages prefer \`expect().not.${matcherName}();\`.`,
380
- `Expected no call to console.${methodName} while also expecting messages.` +
381
- 'Expected no call to console.error but provided messages. ' +
382
- "If you want to make sure a certain message isn't logged prefer the positive. " +
383
- 'By expecting certain messages you automatically expect that no other messages are logged',
384
- // Not interested in a diff but the typings require the 4th parameter.
385
- undefined,
386
- );
387
-
388
- // Ignore skipped messages in e.g. `[condition && 'foo']`
389
- const remainingMessages = expectedMessages.filter((messageOrFalse) => {
390
- return messageOrFalse !== false;
391
- });
392
-
393
- // eslint-disable-next-line no-console
394
- const originalMethod = console[methodName];
395
-
396
- let messagesMatched = 0;
397
- const consoleMatcher = (format: string, ...args: readonly unknown[]) => {
398
- // Ignore legacy root deprecation warnings
399
- // TODO: Remove once we no longer use legacy roots.
400
- if (
401
- format.includes('Use createRoot instead.') ||
402
- format.includes('Use hydrateRoot instead.')
403
- ) {
404
- return;
405
- }
406
- const actualMessage = formatUtil(format, ...args);
407
- const expectedMessage = remainingMessages.shift();
408
- messagesMatched += 1;
409
-
410
- // TODO Remove type once MUI X enables noImplicitAny
411
- let message: string | null = null;
412
- if (expectedMessage === undefined) {
413
- message = `Expected no more error messages but got:\n"${actualMessage}"`;
414
- } else if (!actualMessage.includes(expectedMessage)) {
415
- message = `Expected #${messagesMatched} "${expectedMessage}" to be included in \n"${actualMessage}"`;
416
- }
417
-
418
- if (message !== null) {
419
- const error = new Error(message);
420
-
421
- const { stack: fullStack } = error;
422
- const fullStacktrace = fullStack!.replace(`Error: ${message}\n`, '').split('\n');
423
-
424
- const usefulStacktrace = fullStacktrace
425
- //
426
- // first line points to this frame which is irrelevant for the tester
427
- .slice(1);
428
- const usefulStack = `${message}\n${usefulStacktrace.join('\n')}`;
429
-
430
- error.stack = usefulStack;
431
- unexpectedMessages.push(error);
432
- }
433
- };
434
- // eslint-disable-next-line no-console
435
- console[methodName] = consoleMatcher;
436
-
437
- try {
438
- callback();
439
- } catch (error) {
440
- caughtError = error;
441
- } finally {
442
- // eslint-disable-next-line no-console
443
- console[methodName] = originalMethod;
444
-
445
- // unexpected thrown error takes precedence over unexpected console call
446
- if (caughtError !== null) {
447
- // not the same pattern as described in the block because we don't rethrow in the catch
448
- // eslint-disable-next-line no-unsafe-finally
449
- throw caughtError;
450
- }
451
-
452
- const formatMessages = (messages: ReadonlyArray<Error | string>) => {
453
- const formattedMessages = messages.map((message) => {
454
- if (typeof message === 'string') {
455
- return `"${message}"`;
456
- }
457
- // full Error
458
- return `${message.stack}`;
459
- });
460
- return `\n\n - ${formattedMessages.join('\n\n- ')}`;
461
- };
462
-
463
- const shouldHaveWarned = utils.flag(this, 'negate') !== true;
464
-
465
- // unreachable from expect().not.toWarnDev(messages)
466
- if (unexpectedMessages.length > 0) {
467
- const unexpectedMessageRecordedMessage = `Recorded unexpected console.${methodName} calls: ${formatMessages(
468
- unexpectedMessages,
469
- )}`;
470
- // chai will duplicate the stack frames from the unexpected calls in their assertion error
471
- // it's not ideal but the test failure is located the second to last stack frame
472
- // and the origin of the call is the second stackframe in the stack
473
- this.assert(
474
- // force chai to always trigger an assertion error
475
- !shouldHaveWarned,
476
- unexpectedMessageRecordedMessage,
477
- unexpectedMessageRecordedMessage,
478
- // Not interested in a diff but the typings require the 4th parameter.
479
- undefined,
480
- );
481
- }
482
-
483
- if (shouldHaveWarned) {
484
- this.assert(
485
- remainingMessages.length === 0,
486
- `Could not match the following console.${methodName} calls. ` +
487
- `Make sure previous actions didn't call console.${methodName} by wrapping them in expect(() => {}).not.${matcherName}(): ${formatMessages(
488
- remainingMessages,
489
- )}`,
490
- `Impossible state reached in \`expect().${matcherName}()\`. ` +
491
- `This is a bug in the matcher.`,
492
- // Not interested in a diff but the typings require the 4th parameter.
493
- undefined,
494
- );
495
- }
496
- }
497
- } else {
498
- // nothing to do in prod
499
- // If there are still console calls than our test setup throws.
500
- callback();
501
- }
502
- }
503
-
504
- chaiAPI.Assertion.addMethod(matcherName, matcher);
505
- }
506
-
507
- /**
508
- * @example expect(() => render()).toWarnDev('single message')
509
- * @example expect(() => render()).toWarnDev(['first warning', 'then the second'])
510
- */
511
- addConsoleMatcher('toWarnDev', 'warn');
512
- addConsoleMatcher('toErrorDev', 'error');
513
- };
514
-
515
- export default chaiPlugin;
@@ -1,61 +0,0 @@
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
- export class ErrorBoundary extends React.Component<{ children: React.ReactNode }> {
10
- static propTypes = {
11
- children: PropTypes.node.isRequired,
12
- };
13
-
14
- state = {
15
- error: null,
16
- };
17
-
18
- /**
19
- * @public
20
- */
21
- errors: unknown[] = [];
22
-
23
- static getDerivedStateFromError(error: unknown) {
24
- return { error };
25
- }
26
-
27
- componentDidCatch(error: unknown) {
28
- this.errors.push(error);
29
- }
30
-
31
- render() {
32
- if (this.state.error) {
33
- return null;
34
- }
35
- return this.props.children;
36
- }
37
- }
38
-
39
- /**
40
- * Allows counting how many times the owner of `RenderCounter` rendered or
41
- * a component within the RenderCounter tree "commits" an update.
42
- * @example <RenderCounter ref={getRenderCountRef}>...</RenderCounter>
43
- * getRenderCountRef.current() === 2
44
- */
45
- export const RenderCounter = React.forwardRef<() => number, { children: React.ReactNode }>(
46
- function RenderCounter({ children }, ref) {
47
- const getRenderCountRef = React.useRef(0);
48
- React.useImperativeHandle(ref, () => () => getRenderCountRef.current);
49
-
50
- return (
51
- <React.Profiler
52
- id="render-counter"
53
- onRender={() => {
54
- getRenderCountRef.current += 1;
55
- }}
56
- >
57
- {children}
58
- </React.Profiler>
59
- );
60
- },
61
- );
@@ -1,9 +0,0 @@
1
- // there's probably a broader solution e.g. levering DOMWindow from 'jsdom'
2
- // interface Window extends DOMWindow doesn't work because jsdom typings use
3
- // triple slash directives. Technical dom.lib.d.ts should already have these properties
4
- interface Window {
5
- DragEvent: typeof DragEvent;
6
- Event: typeof Event;
7
- HTMLButtonElement: HTMLButtonElement;
8
- HTMLParagraphElement: HTMLParagraphElement;
9
- }
@@ -1,31 +0,0 @@
1
- /* eslint-env mocha */
2
-
3
- type MUIDescribe<P extends any[]> = {
4
- (...args: P): void;
5
-
6
- skip: (...args: P) => void;
7
- only: (...args: P) => void;
8
- };
9
- export default <P extends any[]>(
10
- message: string,
11
- callback: (...args: P) => void,
12
- ): MUIDescribe<P> => {
13
- const muiDescribe = (...args: P) => {
14
- describe(message, () => {
15
- callback(...args);
16
- });
17
- };
18
-
19
- muiDescribe.skip = (...args: P) => {
20
- describe.skip(message, () => {
21
- callback(...args);
22
- });
23
- };
24
- muiDescribe.only = (...args: P) => {
25
- describe.only(message, () => {
26
- callback(...args);
27
- });
28
- };
29
-
30
- return muiDescribe;
31
- };
@@ -1,31 +0,0 @@
1
- import { expect } from 'chai';
2
- import * as React from 'react';
3
- import * as ReactDOM from 'react-dom';
4
- import { createRenderer } from './createRenderer';
5
-
6
- describe('createRenderer', () => {
7
- const { render } = createRenderer();
8
-
9
- it('allows querying descriptions', () => {
10
- function Component() {
11
- return (
12
- <React.Fragment>
13
- <div id="target" aria-describedby="r:1 r:2 r:3">
14
- I have a description.
15
- </div>
16
- {ReactDOM.createPortal(<div id="r:1">Description 1</div>, document.body)}
17
- {/* The ID format is important here. It would fail `querySelectorAll('#r:2')` and ensures we use `getElementById` */}
18
- <div id="r:2">Description 2</div>
19
- <div id="r:3">Description 3</div>
20
- </React.Fragment>
21
- );
22
- }
23
- const { getAllDescriptionsOf } = render(<Component />);
24
-
25
- const descriptions = getAllDescriptionsOf(document.getElementById('target'));
26
- expect(descriptions).to.have.length(3);
27
- expect(descriptions[0]).to.have.property('id', 'r:1');
28
- expect(descriptions[1]).to.have.property('id', 'r:2');
29
- expect(descriptions[2]).to.have.property('id', 'r:3');
30
- });
31
- });