@mui/internal-test-utils 1.0.18 → 1.0.20

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