@mui/internal-test-utils 1.0.0-dev.20240529-082515-213b5e33ab

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 (148) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/LICENSE +21 -0
  3. package/README.md +9 -0
  4. package/build/.tsbuildinfo +1 -0
  5. package/build/KarmaReporterReactProfiler.d.ts +51 -0
  6. package/build/KarmaReporterReactProfiler.d.ts.map +1 -0
  7. package/build/KarmaReporterReactProfiler.js +68 -0
  8. package/build/KarmaReporterReactProfiler.js.map +1 -0
  9. package/build/components.d.ts +36 -0
  10. package/build/components.d.ts.map +1 -0
  11. package/build/components.js +78 -0
  12. package/build/components.js.map +1 -0
  13. package/build/createDOM.d.ts +3 -0
  14. package/build/createDOM.d.ts.map +1 -0
  15. package/build/createDOM.js +60 -0
  16. package/build/createDOM.js.map +1 -0
  17. package/build/createDescribe.d.ts +8 -0
  18. package/build/createDescribe.d.ts.map +1 -0
  19. package/build/createDescribe.js +22 -0
  20. package/build/createDescribe.js.map +1 -0
  21. package/build/createMount.d.ts +9 -0
  22. package/build/createMount.d.ts.map +1 -0
  23. package/build/createMount.js +120 -0
  24. package/build/createMount.js.map +1 -0
  25. package/build/createRenderer.d.ts +231 -0
  26. package/build/createRenderer.d.ts.map +1 -0
  27. package/build/createRenderer.js +506 -0
  28. package/build/createRenderer.js.map +1 -0
  29. package/build/createRenderer.test.d.ts +2 -0
  30. package/build/createRenderer.test.d.ts.map +1 -0
  31. package/build/createRenderer.test.js +48 -0
  32. package/build/createRenderer.test.js.map +1 -0
  33. package/build/describeConformance.d.ts +152 -0
  34. package/build/describeConformance.d.ts.map +1 -0
  35. package/build/describeConformance.js +815 -0
  36. package/build/describeConformance.js.map +1 -0
  37. package/build/findOutermostIntrinsic.d.ts +14 -0
  38. package/build/findOutermostIntrinsic.d.ts.map +1 -0
  39. package/build/findOutermostIntrinsic.js +22 -0
  40. package/build/findOutermostIntrinsic.js.map +1 -0
  41. package/build/findOutermostIntrinsic.test.d.ts +2 -0
  42. package/build/findOutermostIntrinsic.test.d.ts.map +1 -0
  43. package/build/findOutermostIntrinsic.test.js +70 -0
  44. package/build/findOutermostIntrinsic.test.js.map +1 -0
  45. package/build/fireDiscreteEvent.d.ts +7 -0
  46. package/build/fireDiscreteEvent.d.ts.map +1 -0
  47. package/build/fireDiscreteEvent.js +98 -0
  48. package/build/fireDiscreteEvent.js.map +1 -0
  49. package/build/flushMicrotasks.d.ts +2 -0
  50. package/build/flushMicrotasks.d.ts.map +1 -0
  51. package/build/flushMicrotasks.js +11 -0
  52. package/build/flushMicrotasks.js.map +1 -0
  53. package/build/focusVisible.d.ts +7 -0
  54. package/build/focusVisible.d.ts.map +1 -0
  55. package/build/focusVisible.js +33 -0
  56. package/build/focusVisible.js.map +1 -0
  57. package/build/index.d.ts +18 -0
  58. package/build/index.d.ts.map +1 -0
  59. package/build/index.js +59 -0
  60. package/build/index.js.map +1 -0
  61. package/build/init.d.ts +2 -0
  62. package/build/init.d.ts.map +1 -0
  63. package/build/init.js +42 -0
  64. package/build/init.js.map +1 -0
  65. package/build/initMatchers.d.ts +81 -0
  66. package/build/initMatchers.d.ts.map +1 -0
  67. package/build/initMatchers.js +431 -0
  68. package/build/initMatchers.js.map +1 -0
  69. package/build/initMatchers.test.d.ts +2 -0
  70. package/build/initMatchers.test.d.ts.map +1 -0
  71. package/build/initMatchers.test.js +103 -0
  72. package/build/initMatchers.test.js.map +1 -0
  73. package/build/initPlaywrightMatchers.d.ts +25 -0
  74. package/build/initPlaywrightMatchers.d.ts.map +1 -0
  75. package/build/initPlaywrightMatchers.js +63 -0
  76. package/build/initPlaywrightMatchers.js.map +1 -0
  77. package/build/mochaHooks.d.ts +25 -0
  78. package/build/mochaHooks.d.ts.map +1 -0
  79. package/build/mochaHooks.js +171 -0
  80. package/build/mochaHooks.js.map +1 -0
  81. package/build/mochaHooks.test.d.ts +2 -0
  82. package/build/mochaHooks.test.d.ts.map +1 -0
  83. package/build/mochaHooks.test.js +112 -0
  84. package/build/mochaHooks.test.js.map +1 -0
  85. package/build/setup.d.ts +2 -0
  86. package/build/setup.d.ts.map +1 -0
  87. package/build/setup.js +10 -0
  88. package/build/setup.js.map +1 -0
  89. package/build/setupBabel.d.ts +2 -0
  90. package/build/setupBabel.d.ts.map +1 -0
  91. package/build/setupBabel.js +5 -0
  92. package/build/setupBabel.js.map +1 -0
  93. package/build/setupBabelPlaywright.d.ts +2 -0
  94. package/build/setupBabelPlaywright.d.ts.map +1 -0
  95. package/build/setupBabelPlaywright.js +11 -0
  96. package/build/setupBabelPlaywright.js.map +1 -0
  97. package/build/setupJSDOM.d.ts +7 -0
  98. package/build/setupJSDOM.d.ts.map +1 -0
  99. package/build/setupJSDOM.js +17 -0
  100. package/build/setupJSDOM.js.map +1 -0
  101. package/build/setupKarma.d.ts +2 -0
  102. package/build/setupKarma.d.ts.map +1 -0
  103. package/build/setupKarma.js +56 -0
  104. package/build/setupKarma.js.map +1 -0
  105. package/build/until.d.ts +2 -0
  106. package/build/until.d.ts.map +1 -0
  107. package/build/until.js +26 -0
  108. package/build/until.js.map +1 -0
  109. package/build/until.test.d.ts +2 -0
  110. package/build/until.test.d.ts.map +1 -0
  111. package/build/until.test.js +118 -0
  112. package/build/until.test.js.map +1 -0
  113. package/build/userEvent.d.ts +8 -0
  114. package/build/userEvent.d.ts.map +1 -0
  115. package/build/userEvent.js +61 -0
  116. package/build/userEvent.js.map +1 -0
  117. package/package.json +76 -0
  118. package/src/KarmaReporterReactProfiler.js +81 -0
  119. package/src/components.tsx +61 -0
  120. package/src/createDOM.d.ts +9 -0
  121. package/src/createDOM.js +67 -0
  122. package/src/createDescribe.ts +31 -0
  123. package/src/createMount.tsx +136 -0
  124. package/src/createRenderer.test.js +31 -0
  125. package/src/createRenderer.tsx +737 -0
  126. package/src/describeConformance.tsx +1117 -0
  127. package/src/findOutermostIntrinsic.test.js +68 -0
  128. package/src/findOutermostIntrinsic.ts +19 -0
  129. package/src/fireDiscreteEvent.ts +76 -0
  130. package/src/flushMicrotasks.ts +8 -0
  131. package/src/focusVisible.ts +28 -0
  132. package/src/index.ts +24 -0
  133. package/src/init.js +15 -0
  134. package/src/initMatchers.test.js +126 -0
  135. package/src/initMatchers.ts +658 -0
  136. package/src/initPlaywrightMatchers.ts +96 -0
  137. package/src/mochaHooks.js +209 -0
  138. package/src/mochaHooks.test.js +113 -0
  139. package/src/setup.js +10 -0
  140. package/src/setupBabel.js +3 -0
  141. package/src/setupBabelPlaywright.js +10 -0
  142. package/src/setupJSDOM.js +20 -0
  143. package/src/setupKarma.js +65 -0
  144. package/src/until.js +28 -0
  145. package/src/until.test.js +120 -0
  146. package/src/userEvent.ts +35 -0
  147. package/tsconfig.build.json +17 -0
  148. package/tsconfig.json +12 -0
@@ -0,0 +1,658 @@
1
+ import chai, { AssertionError } from 'chai';
2
+ import chaiDom from 'chai-dom';
3
+ import _ from 'lodash';
4
+ import { isInaccessible } from '@testing-library/dom';
5
+ import { prettyDOM } from '@testing-library/react/pure';
6
+ import { computeAccessibleDescription, computeAccessibleName } from 'dom-accessibility-api';
7
+ import formatUtil from 'format-util';
8
+
9
+ chai.use(chaiDom);
10
+
11
+ const isKarma = Boolean(process.env.KARMA);
12
+
13
+ // https://stackoverflow.com/a/46755166/3406963
14
+ declare global {
15
+ namespace Chai {
16
+ interface Assertion {
17
+ /**
18
+ * Checks if the element in question is considered `aria-hidden`.
19
+ * Does not replace accessibility check as that requires display/visibility/layout
20
+ * @deprecated Use `inaccessible` + `visible` instead
21
+ */
22
+ toBeAriaHidden(): void;
23
+ /**
24
+ * Checks `expectedStyle` is a subset of the elements inline style i.e. `element.style`.
25
+ * @example expect(element).toHaveInlineStyle({ width: '200px' })
26
+ */
27
+ toHaveInlineStyle(
28
+ expectedStyle: Partial<
29
+ Record<
30
+ Exclude<
31
+ keyof CSSStyleDeclaration,
32
+ | 'getPropertyPriority'
33
+ | 'getPropertyValue'
34
+ | 'item'
35
+ | 'removeProperty'
36
+ | 'setProperty'
37
+ | number
38
+ >,
39
+ string
40
+ >
41
+ >,
42
+ ): void;
43
+ /**
44
+ * Checks `expectedStyle` is a subset of the elements computed style i.e. `window.getComputedStyle(element)`.
45
+ * @example expect(element).toHaveComputedStyle({ width: '200px' })
46
+ */
47
+ toHaveComputedStyle(
48
+ expectedStyle: Partial<
49
+ Record<
50
+ Exclude<
51
+ keyof CSSStyleDeclaration,
52
+ | 'getPropertyPriority'
53
+ | 'getPropertyValue'
54
+ | 'item'
55
+ | 'removeProperty'
56
+ | 'setProperty'
57
+ | number
58
+ >,
59
+ string
60
+ >
61
+ >,
62
+ ): void;
63
+ /**
64
+ * Check if an element's [`visibility`](https://developer.mozilla.org/en-US/docs/Web/CSS/visibility) is not `hidden` or `collapsed`.
65
+ */
66
+ toBeVisible(): void;
67
+ /**
68
+ * Check if an element's [`visibility`](https://developer.mozilla.org/en-US/docs/Web/CSS/visibility) is `hidden` or `collapsed`.
69
+ */
70
+ toBeHidden(): void;
71
+ /**
72
+ * Checks if the element is inaccessible.
73
+ *
74
+ * Elements are considered inaccessible if they either:
75
+ * - have [`visibility`](https://developer.mozilla.org/en-US/docs/Web/CSS/visibility) `hidden`
76
+ * - have [`display`](https://developer.mozilla.org/en-US/docs/Web/CSS/display) `none`
77
+ * - have `aria-hidden` `true` or any of their parents
78
+ *
79
+ * @see [Excluding Elements from the Accessibility Tree](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion)
80
+ */
81
+ toBeInaccessible(): void;
82
+ toHaveAccessibleDescription(description: string): void;
83
+ /**
84
+ * Checks if the accessible name computation (according to `accname` spec)
85
+ * matches the expectation.
86
+ *
87
+ * @see https://www.w3.org/TR/accname-1.2/
88
+ * @param name
89
+ */
90
+ toHaveAccessibleName(name: string): void;
91
+ /**
92
+ * Checks if the element is actually focused i.e. `document.activeElement` is equal to the actual element.
93
+ */
94
+ toHaveFocus(): void;
95
+ /**
96
+ * Checks if the element is the active-descendant of the active element.
97
+ */
98
+ toHaveVirtualFocus(): void;
99
+ /**
100
+ * Matches calls to `console.warn` in the asserted callback.
101
+ *
102
+ * @example expect(() => render()).not.toWarnDev()
103
+ * @example expect(() => render()).toWarnDev('single message')
104
+ * @example expect(() => render()).toWarnDev(['first warning', 'then the second'])
105
+ */
106
+ toWarnDev(messages?: string | readonly (string | boolean)[]): void;
107
+ /**
108
+ * Matches calls to `console.error` in the asserted callback.
109
+ *
110
+ * @example expect(() => render()).not.toErrorDev()
111
+ * @example expect(() => render()).toErrorDev('single message')
112
+ * @example expect(() => render()).toErrorDev(['first warning', 'then the second'])
113
+ */
114
+ toErrorDev(messages?: string | readonly (string | boolean)[]): void;
115
+ /**
116
+ * Asserts that the given callback throws an error matching the given message in development (process.env.NODE_ENV !== 'production').
117
+ * In production it expects a minified error.
118
+ */
119
+ toThrowMinified(message: string): void;
120
+ }
121
+ }
122
+ }
123
+
124
+ function isInJSDOM() {
125
+ return /jsdom/.test(window.navigator.userAgent);
126
+ }
127
+
128
+ // chai#utils.elToString that looks like stringified elements in testing-library
129
+ function elementToString(element: Element | null | undefined) {
130
+ if (typeof element?.nodeType === 'number') {
131
+ return prettyDOM(element, undefined, { highlight: !isKarma, maxDepth: 1 });
132
+ }
133
+ return String(element);
134
+ }
135
+ chai.use((chaiAPI, utils) => {
136
+ const blockElements = new Set([
137
+ 'html',
138
+ 'address',
139
+ 'blockquote',
140
+ 'body',
141
+ 'dd',
142
+ 'div',
143
+ 'dl',
144
+ 'dt',
145
+ 'fieldset',
146
+ 'form',
147
+ 'frame',
148
+ 'frameset',
149
+ 'h1',
150
+ 'h2',
151
+ 'h3',
152
+ 'h4',
153
+ 'h5',
154
+ 'h6',
155
+ 'noframes',
156
+ 'ol',
157
+ 'p',
158
+ 'ul',
159
+ 'center',
160
+ 'dir',
161
+ 'hr',
162
+ 'menu',
163
+ 'pre',
164
+ ]);
165
+
166
+ function pretendVisibleGetComputedStyle(element: Element): CSSStyleDeclaration {
167
+ // `CSSStyleDeclaration` is not constructable
168
+ // https://stackoverflow.com/a/52732909/3406963
169
+ // this is not equivalent to the declaration from `getComputedStyle`
170
+ // for example `getComputedStyle` would return a readonly declaration
171
+ // let's hope this doesn't get passed around until it's no longer clear where it comes from
172
+ const declaration = document.createElement('span').style;
173
+
174
+ // initial values
175
+ declaration.content = '';
176
+ // technically it's `inline`. We partially apply the default user agent sheet (chrome) here
177
+ // we're only interested in elements that use block
178
+ declaration.display = blockElements.has(element.tagName) ? 'block' : 'inline';
179
+ declaration.visibility = 'visible';
180
+
181
+ return declaration;
182
+ }
183
+
184
+ // better diff view for expect(element).to.equal(document.activeElement)
185
+ chai.Assertion.addMethod('toHaveFocus', function elementIsFocused() {
186
+ const element = utils.flag(this, 'object');
187
+
188
+ this.assert(
189
+ element === document.activeElement,
190
+ // karma does not show the diff like mocha does
191
+ `expected element to have focus${isKarma ? '\nexpected #{exp}\nactual: #{act}' : ''}`,
192
+ `expected element to NOT have focus \n${elementToString(element)}`,
193
+ elementToString(element),
194
+ elementToString(document.activeElement),
195
+ );
196
+ });
197
+
198
+ chai.Assertion.addMethod('toHaveVirtualFocus', function elementIsVirtuallyFocused() {
199
+ const element = utils.flag(this, 'object');
200
+ const id = element.getAttribute('id');
201
+
202
+ const virtuallyFocusedElementId = document.activeElement!.getAttribute('aria-activedescendant');
203
+
204
+ this.assert(
205
+ virtuallyFocusedElementId === id,
206
+ `expected element to be virtually focused\nexpected id #{exp}\n${
207
+ virtuallyFocusedElementId === null
208
+ ? `activeElement: ${elementToString(document.activeElement)}`
209
+ : 'actual id: #{act}'
210
+ }`,
211
+ 'expected element to NOT to be virtually focused',
212
+ id,
213
+ virtuallyFocusedElementId,
214
+ virtuallyFocusedElementId !== null,
215
+ );
216
+ });
217
+
218
+ chai.Assertion.addMethod('toBeAriaHidden', function elementIsAccessible() {
219
+ const element = utils.flag(this, 'object');
220
+
221
+ // used for debugging failed assertions, will either point to the top most node
222
+ // or the node that had aria-hidden="true"
223
+ let previousNode = element;
224
+ let currentNode = element;
225
+ let ariaHidden = false;
226
+ // "An element is considered hidden if it, or any of its ancestors are not
227
+ // rendered or have their aria-hidden attribute value set to true."
228
+ // -- https://www.w3.org/TR/wai-aria-1.1/#aria-hidden
229
+ while (
230
+ currentNode !== null &&
231
+ // stopping at <html /> so that failed assertion message only prints
232
+ // <body /> or below. use cases for aria-hidden on <html /> are unknown
233
+ currentNode !== document.documentElement &&
234
+ ariaHidden === false
235
+ ) {
236
+ ariaHidden = currentNode.getAttribute('aria-hidden') === 'true';
237
+ previousNode = currentNode;
238
+ currentNode = currentNode.parentElement;
239
+ }
240
+
241
+ this.assert(
242
+ ariaHidden === true,
243
+ `expected \n${elementToString(element)} to be aria-hidden`,
244
+ `expected \n${elementToString(element)} to not be aria-hidden, but \n${elementToString(
245
+ previousNode,
246
+ )} had aria-hidden="true" instead`,
247
+ // Not interested in a diff but the typings require the 4th parameter.
248
+ undefined,
249
+ );
250
+ });
251
+
252
+ chai.Assertion.addMethod('toBeInaccessible', function elementIsAccessible() {
253
+ const element = utils.flag(this, 'object');
254
+
255
+ const inaccessible = isInaccessible(element);
256
+
257
+ this.assert(
258
+ inaccessible === true,
259
+ `expected \n${elementToString(element)} to be inaccessible but it was accessible`,
260
+ `expected \n${elementToString(element)} to be accessible but it was inaccessible`,
261
+ // Not interested in a diff but the typings require the 4th parameter.
262
+ undefined,
263
+ );
264
+ });
265
+
266
+ chai.Assertion.addMethod('toHaveAccessibleName', function hasAccessibleName(expectedName) {
267
+ const root = utils.flag(this, 'object');
268
+ // make sure it's an Element
269
+ new chai.Assertion(root.nodeType, `Expected an Element but got '${String(root)}'`).to.equal(1);
270
+
271
+ const actualName = computeAccessibleName(root, {
272
+ computedStyleSupportsPseudoElements: !isInJSDOM(),
273
+ // in local development we pretend to be visible. full getComputedStyle is
274
+ // expensive and reserved for CI
275
+ getComputedStyle: process.env.CI ? undefined : pretendVisibleGetComputedStyle,
276
+ });
277
+
278
+ this.assert(
279
+ actualName === expectedName,
280
+ `expected \n${elementToString(root)} to have accessible name #{exp} but got #{act} instead.`,
281
+ `expected \n${elementToString(root)} not to have accessible name #{exp}.`,
282
+ expectedName,
283
+ actualName,
284
+ );
285
+ });
286
+
287
+ chai.Assertion.addMethod(
288
+ 'toHaveAccessibleDescription',
289
+ function hasAccessibleDescription(expectedDescription) {
290
+ const root = utils.flag(this, 'object');
291
+ // make sure it's an Element
292
+ new chai.Assertion(root.nodeType, `Expected an Element but got '${String(root)}'`).to.equal(
293
+ 1,
294
+ );
295
+
296
+ const actualDescription = computeAccessibleDescription(root, {
297
+ // in local development we pretend to be visible. full getComputedStyle is
298
+ // expensive and reserved for CI
299
+ getComputedStyle: process.env.CI ? undefined : pretendVisibleGetComputedStyle,
300
+ });
301
+
302
+ const possibleDescriptionComputationMessage = root.hasAttribute('title')
303
+ ? ' computeAccessibleDescription can be misleading when a `title` attribute is used. This might be a bug in `dom-accessibility-api`.'
304
+ : '';
305
+ this.assert(
306
+ actualDescription === expectedDescription,
307
+ `expected \n${elementToString(
308
+ root,
309
+ )} to have accessible description #{exp} but got #{act} instead.${possibleDescriptionComputationMessage}`,
310
+ `expected \n${elementToString(
311
+ root,
312
+ )} not to have accessible description #{exp}.${possibleDescriptionComputationMessage}`,
313
+ expectedDescription,
314
+ actualDescription,
315
+ );
316
+ },
317
+ );
318
+
319
+ /**
320
+ * Correct name for `to.be.visible`
321
+ */
322
+ chai.Assertion.addMethod('toBeVisible', function toBeVisible() {
323
+ // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-unused-expressions
324
+ new chai.Assertion(this._obj).to.be.visible;
325
+ });
326
+
327
+ /**
328
+ * Correct name for `not.to.be.visible`
329
+ */
330
+ chai.Assertion.addMethod('toBeHidden', function toBeHidden() {
331
+ // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-unused-expressions
332
+ new chai.Assertion(this._obj).not.to.be.visible;
333
+ });
334
+
335
+ function assertMatchingStyles(
336
+ this: Chai.AssertionStatic,
337
+ actualStyleDeclaration: CSSStyleDeclaration,
338
+ expectedStyleUnnormalized: Record<string, string>,
339
+ options: { styleTypeHint: string },
340
+ ): void {
341
+ const { styleTypeHint } = options;
342
+
343
+ // Compare objects using hyphen case.
344
+ // This is closer to actual CSS and required for getPropertyValue anyway.
345
+ const expectedStyle: Record<string, string> = {};
346
+ Object.keys(expectedStyleUnnormalized).forEach((cssProperty) => {
347
+ const hyphenCasedPropertyName = _.kebabCase(cssProperty);
348
+ const isVendorPrefixed = /^(moz|ms|o|webkit)-/.test(hyphenCasedPropertyName);
349
+ const propertyName = isVendorPrefixed
350
+ ? `-${hyphenCasedPropertyName}`
351
+ : hyphenCasedPropertyName;
352
+ expectedStyle[propertyName] = expectedStyleUnnormalized[cssProperty];
353
+ });
354
+
355
+ const shorthandProperties = new Set([
356
+ 'all',
357
+ 'animation',
358
+ 'background',
359
+ 'border',
360
+ 'border-block-end',
361
+ 'border-block-start',
362
+ 'border-bottom',
363
+ 'border-color',
364
+ 'border-image',
365
+ 'border-inline-end',
366
+ 'border-inline-start',
367
+ 'border-left',
368
+ 'border-radius',
369
+ 'border-right',
370
+ 'border-style',
371
+ 'border-top',
372
+ 'border-width',
373
+ 'column-rule',
374
+ 'columns',
375
+ 'flex',
376
+ 'flex-flow',
377
+ 'font',
378
+ 'gap',
379
+ 'grid',
380
+ 'grid-area',
381
+ 'grid-column',
382
+ 'grid-row',
383
+ 'grid-template',
384
+ 'list-style',
385
+ 'margin',
386
+ 'mask',
387
+ 'offset',
388
+ 'outline',
389
+ 'overflow',
390
+ 'padding',
391
+ 'place-content',
392
+ 'place-items',
393
+ 'place-self',
394
+ 'scroll-margin',
395
+ 'scroll-padding',
396
+ 'text-decoration',
397
+ 'text-emphasis',
398
+ 'transition',
399
+ ]);
400
+ const usedShorthandProperties = Object.keys(expectedStyle).filter((cssProperty) => {
401
+ return shorthandProperties.has(cssProperty);
402
+ });
403
+ if (usedShorthandProperties.length > 0) {
404
+ throw new Error(
405
+ [
406
+ `Shorthand properties are not supported in ${styleTypeHint} styles matchers since browsers can compute them differently. `,
407
+ 'Use longhand properties instead for the follow shorthand properties:\n',
408
+ usedShorthandProperties
409
+ .map((cssProperty) => {
410
+ return `- https://developer.mozilla.org/en-US/docs/Web/CSS/${cssProperty}#constituent_properties`;
411
+ })
412
+ .join('\n'),
413
+ ].join(''),
414
+ );
415
+ }
416
+
417
+ const actualStyle: Record<string, string> = {};
418
+ Object.keys(expectedStyle).forEach((cssProperty) => {
419
+ actualStyle[cssProperty] = actualStyleDeclaration.getPropertyValue(cssProperty);
420
+ });
421
+
422
+ const jsdomHint =
423
+ 'Styles in JSDOM e.g. from `test:unit` are often misleading since JSDOM does not implement the Cascade nor actual CSS property value computation. ' +
424
+ 'If results differ between real browsers and JSDOM, skip the test in JSDOM e.g. `if (/jsdom/.test(window.navigator.userAgent)) this.skip();`';
425
+ const shorthandHint =
426
+ 'Browsers can compute shorthand properties differently. Prefer longhand properties e.g. `borderTopColor`, `borderRightColor` etc. instead of `border` or `border-color`.';
427
+ const messageHint = `${jsdomHint}\n${shorthandHint}`;
428
+
429
+ if (isKarma) {
430
+ // `#{exp}` and `#{act}` placeholders escape the newlines
431
+ const expected = JSON.stringify(expectedStyle, null, 2);
432
+ const actual = JSON.stringify(actualStyle, null, 2);
433
+ // karma's `dots` reporter does not support diffs
434
+ this.assert(
435
+ // TODO Fix upstream docs/types
436
+ (utils as any).eql(actualStyle, expectedStyle),
437
+ `expected ${styleTypeHint} style of #{this} did not match\nExpected:\n${expected}\nActual:\n${actual}\n\n\n${messageHint}`,
438
+ `expected #{this} to not have ${styleTypeHint} style\n${expected}\n\n\n${messageHint}`,
439
+ expectedStyle,
440
+ actualStyle,
441
+ );
442
+ } else {
443
+ this.assert(
444
+ // TODO Fix upstream docs/types
445
+ (utils as any).eql(actualStyle, expectedStyle),
446
+ `expected #{this} to have ${styleTypeHint} style #{exp} \n\n${messageHint}`,
447
+ `expected #{this} not to have ${styleTypeHint} style #{exp}${messageHint}`,
448
+ expectedStyle,
449
+ actualStyle,
450
+ true,
451
+ );
452
+ }
453
+ }
454
+
455
+ chai.Assertion.addMethod(
456
+ 'toHaveInlineStyle',
457
+ function toHaveInlineStyle(expectedStyleUnnormalized: Record<string, string>) {
458
+ const element = utils.flag(this, 'object') as HTMLElement;
459
+ if (element?.nodeType !== 1) {
460
+ // Same pre-condition for negated and unnegated assertion
461
+ throw new AssertionError(`Expected an Element but got ${String(element)}`);
462
+ }
463
+
464
+ assertMatchingStyles.call(this, element.style, expectedStyleUnnormalized, {
465
+ styleTypeHint: 'inline',
466
+ });
467
+ },
468
+ );
469
+
470
+ chai.Assertion.addMethod(
471
+ 'toHaveComputedStyle',
472
+ function toHaveComputedStyle(expectedStyleUnnormalized: Record<string, string>) {
473
+ const element = utils.flag(this, 'object') as HTMLElement;
474
+ if (element?.nodeType !== 1) {
475
+ // Same pre-condition for negated and unnegated assertion
476
+ throw new AssertionError(`Expected an Element but got ${String(element)}`);
477
+ }
478
+ const computedStyle = element.ownerDocument.defaultView!.getComputedStyle(element);
479
+
480
+ assertMatchingStyles.call(this, computedStyle, expectedStyleUnnormalized, {
481
+ styleTypeHint: 'computed',
482
+ });
483
+ },
484
+ );
485
+
486
+ chai.Assertion.addMethod('toThrowMinified', function toThrowMinified(expectedDevMessage) {
487
+ // TODO: Investigate if `as any` can be removed after https://github.com/DefinitelyTyped/DefinitelyTyped/issues/48634 is resolved.
488
+ if (process.env.NODE_ENV !== 'production') {
489
+ (this as any).to.throw(expectedDevMessage);
490
+ } else {
491
+ utils.flag(
492
+ this,
493
+ 'message',
494
+ "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.",
495
+ );
496
+ // TODO: Investigate if `as any` can be removed after https://github.com/DefinitelyTyped/DefinitelyTyped/issues/48634 is resolved.
497
+ (this as any).to.throw('Minified MUI error', 'helper');
498
+ }
499
+ });
500
+ });
501
+
502
+ chai.use((chaiAPI, utils) => {
503
+ function addConsoleMatcher(matcherName: string, methodName: 'error' | 'warn') {
504
+ /**
505
+ * @param {string[]} expectedMessages
506
+ */
507
+ function matcher(this: Chai.AssertionStatic, expectedMessagesInput = []) {
508
+ // documented pattern to get the actual value of the assertion
509
+ // eslint-disable-next-line no-underscore-dangle
510
+ const callback = this._obj;
511
+
512
+ if (process.env.NODE_ENV !== 'production') {
513
+ const expectedMessages =
514
+ typeof expectedMessagesInput === 'string'
515
+ ? [expectedMessagesInput]
516
+ : expectedMessagesInput.slice();
517
+ const unexpectedMessages: Error[] = [];
518
+ // TODO Remove type once MUI X enables noImplicitAny
519
+ let caughtError: unknown | null = null;
520
+
521
+ this.assert(
522
+ expectedMessages.length > 0,
523
+ `Expected to call console.${methodName} but didn't provide messages. ` +
524
+ `If you don't expect any messages prefer \`expect().not.${matcherName}();\`.`,
525
+ `Expected no call to console.${methodName} while also expecting messages.` +
526
+ 'Expected no call to console.error but provided messages. ' +
527
+ "If you want to make sure a certain message isn't logged prefer the positive. " +
528
+ 'By expecting certain messages you automatically expect that no other messages are logged',
529
+ // Not interested in a diff but the typings require the 4th parameter.
530
+ undefined,
531
+ );
532
+
533
+ // Ignore skipped messages in e.g. `[condition && 'foo']`
534
+ const remainingMessages = expectedMessages.filter((messageOrFalse) => {
535
+ return messageOrFalse !== false;
536
+ });
537
+
538
+ // eslint-disable-next-line no-console
539
+ const originalMethod = console[methodName];
540
+
541
+ let messagesMatched = 0;
542
+ const consoleMatcher = (format: string, ...args: readonly unknown[]) => {
543
+ // Ignore legacy root deprecation warnings
544
+ // TODO: Remove once we no longer use legacy roots.
545
+ if (
546
+ format.indexOf('Use createRoot instead.') !== -1 ||
547
+ format.indexOf('Use hydrateRoot instead.') !== -1
548
+ ) {
549
+ return;
550
+ }
551
+ const actualMessage = formatUtil(format, ...args);
552
+ const expectedMessage = remainingMessages.shift();
553
+ messagesMatched += 1;
554
+
555
+ // TODO Remove type once MUI X enables noImplicitAny
556
+ let message: string | null = null;
557
+ if (expectedMessage === undefined) {
558
+ message = `Expected no more error messages but got:\n"${actualMessage}"`;
559
+ } else if (!actualMessage.includes(expectedMessage)) {
560
+ message = `Expected #${messagesMatched} "${expectedMessage}" to be included in \n"${actualMessage}"`;
561
+ }
562
+
563
+ if (message !== null) {
564
+ const error = new Error(message);
565
+
566
+ const { stack: fullStack } = error;
567
+ const fullStacktrace = fullStack!.replace(`Error: ${message}\n`, '').split('\n');
568
+
569
+ const usefulStacktrace = fullStacktrace
570
+ //
571
+ // first line points to this frame which is irrelevant for the tester
572
+ .slice(1);
573
+ const usefulStack = `${message}\n${usefulStacktrace.join('\n')}`;
574
+
575
+ error.stack = usefulStack;
576
+ unexpectedMessages.push(error);
577
+ }
578
+ };
579
+ // eslint-disable-next-line no-console
580
+ console[methodName] = consoleMatcher;
581
+
582
+ try {
583
+ callback();
584
+ } catch (error) {
585
+ caughtError = error;
586
+ } finally {
587
+ // eslint-disable-next-line no-console
588
+ console[methodName] = originalMethod;
589
+
590
+ // unexpected thrown error takes precedence over unexpected console call
591
+ if (caughtError !== null) {
592
+ // not the same pattern as described in the block because we don't rethrow in the catch
593
+ // eslint-disable-next-line no-unsafe-finally
594
+ throw caughtError;
595
+ }
596
+
597
+ const formatMessages = (messages: ReadonlyArray<Error | string>) => {
598
+ const formattedMessages = messages.map((message) => {
599
+ if (typeof message === 'string') {
600
+ return `"${message}"`;
601
+ }
602
+ // full Error
603
+ return `${message.stack}`;
604
+ });
605
+ return `\n\n - ${formattedMessages.join('\n\n- ')}`;
606
+ };
607
+
608
+ const shouldHaveWarned = utils.flag(this, 'negate') !== true;
609
+
610
+ // unreachable from expect().not.toWarnDev(messages)
611
+ if (unexpectedMessages.length > 0) {
612
+ const unexpectedMessageRecordedMessage = `Recorded unexpected console.${methodName} calls: ${formatMessages(
613
+ unexpectedMessages,
614
+ )}`;
615
+ // chai will duplicate the stack frames from the unexpected calls in their assertion error
616
+ // it's not ideal but the test failure is located the second to last stack frame
617
+ // and the origin of the call is the second stackframe in the stack
618
+ this.assert(
619
+ // force chai to always trigger an assertion error
620
+ !shouldHaveWarned,
621
+ unexpectedMessageRecordedMessage,
622
+ unexpectedMessageRecordedMessage,
623
+ // Not interested in a diff but the typings require the 4th parameter.
624
+ undefined,
625
+ );
626
+ }
627
+
628
+ if (shouldHaveWarned) {
629
+ this.assert(
630
+ remainingMessages.length === 0,
631
+ `Could not match the following console.${methodName} calls. ` +
632
+ `Make sure previous actions didn't call console.${methodName} by wrapping them in expect(() => {}).not.${matcherName}(): ${formatMessages(
633
+ remainingMessages,
634
+ )}`,
635
+ `Impossible state reached in \`expect().${matcherName}()\`. ` +
636
+ `This is a bug in the matcher.`,
637
+ // Not interested in a diff but the typings require the 4th parameter.
638
+ undefined,
639
+ );
640
+ }
641
+ }
642
+ } else {
643
+ // nothing to do in prod
644
+ // If there are still console calls than our test setup throws.
645
+ callback();
646
+ }
647
+ }
648
+
649
+ chai.Assertion.addMethod(matcherName, matcher);
650
+ }
651
+
652
+ /**
653
+ * @example expect(() => render()).toWarnDev('single message')
654
+ * @example expect(() => render()).toWarnDev(['first warning', 'then the second'])
655
+ */
656
+ addConsoleMatcher('toWarnDev', 'warn');
657
+ addConsoleMatcher('toErrorDev', 'error');
658
+ });