Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

test-setup.ts

66 lines2.0 KB

1import '@testing-library/jest-dom/vitest'
2import { cleanup } from '@solidjs/testing-library'
3import { afterEach, beforeEach, vi } from 'vitest'
4​
5const scrollToDescriptor = Object.getOwnPropertyDescriptor(
6 HTMLElement.prototype,
7 'scrollTo',
8)
9const isList = (element: HTMLElement) =>
10 element.matches(
11 '.tsqd-queries-overflow-container, .tsqd-mutations-overflow-container, .test-virtual-list',
12 )
13​
14beforeEach(() => {
15 vi.stubGlobal('CSS', { ...globalThis.CSS, highlights: new Map() })
16 vi.stubGlobal('Highlight', Set)
17 vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(
18 function (this: HTMLElement) {
19 return isList(this) ? 410 : 0
20 },
21 )
22 vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(
23 function (this: HTMLElement) {
24 return isList(this) ? 1000 : 0
25 },
26 )
27 vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(
28 function (this: HTMLElement) {
29 return this.hasAttribute('data-index')
30 ? Number(this.firstElementChild?.getAttribute('data-height') ?? 28)
31 : 0
32 },
33 )
34 vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(
35 function (this: HTMLElement) {
36 if (!isList(this)) return 0
37 const content = this.firstElementChild
38 return content instanceof HTMLElement
39 ? Number.parseFloat(content.style.height) || 0
40 : 0
41 },
42 )
43 Object.defineProperty(HTMLElement.prototype, 'scrollTo', {
44 configurable: true,
45 value(this: HTMLElement, options: ScrollToOptions) {
46 const next = Math.max(
47 0,
48 Math.min(options.top ?? 0, this.scrollHeight - this.clientHeight),
49 )
50 if (next !== this.scrollTop) {
51 this.scrollTop = next
52 this.dispatchEvent(new Event('scroll'))
53 }
54 },
55 })
56})
57​
58afterEach(() => {
59 cleanup()
60 vi.unstubAllGlobals()
61 if (scrollToDescriptor) {
62 Object.defineProperty(HTMLElement.prototype, 'scrollTo', scrollToDescriptor)
63 } else {
64 Reflect.deleteProperty(HTMLElement.prototype, 'scrollTo')
65 }
66})