46 lines
1.7 KiB
TypeScript
46 lines
1.7 KiB
TypeScript
import { afterEach, expect } from 'vitest';
|
||
import { cleanup } from '@testing-library/react';
|
||
import * as matchers from '@testing-library/jest-dom/matchers';
|
||
|
||
/**
|
||
* 组件测试的全局准备。
|
||
*
|
||
* 三件事,每件都对应一类会串味的状态:
|
||
* 1. 每个用例后卸载组件树(不卸载的话下一个用例的 getByText 会命中上一个的 DOM)
|
||
* 2. 重置 zustand store(它是模块级单例,跨用例共享)
|
||
* 3. 提供 matchMedia —— jsdom 没有实现它,而 useIsNarrow 直接调
|
||
*/
|
||
expect.extend(matchers);
|
||
|
||
afterEach(() => {
|
||
cleanup();
|
||
});
|
||
|
||
/**
|
||
* jsdom 不实现 matchMedia。useIsNarrow 会直接调它并挂 change 监听,
|
||
* 缺了就抛 `matchMedia is not a function`,整个测试文件挂掉。
|
||
*
|
||
* 默认返回 false(宽屏)。要测窄屏的用例用 setViewport(true) 覆盖。
|
||
*/
|
||
function installMatchMedia(narrow: boolean) {
|
||
const listeners = new Set<(e: MediaQueryListEvent) => void>();
|
||
(window as any).matchMedia = (query: string) => ({
|
||
matches: narrow,
|
||
media: query,
|
||
onchange: null,
|
||
addEventListener: (_: string, cb: (e: MediaQueryListEvent) => void) => listeners.add(cb),
|
||
removeEventListener: (_: string, cb: (e: MediaQueryListEvent) => void) => listeners.delete(cb),
|
||
// 老式 API,某些库仍在用
|
||
addListener: (cb: (e: MediaQueryListEvent) => void) => listeners.add(cb),
|
||
removeListener: (cb: (e: MediaQueryListEvent) => void) => listeners.delete(cb),
|
||
dispatchEvent: () => false
|
||
});
|
||
}
|
||
|
||
installMatchMedia(false);
|
||
|
||
/** 让当前测试文件里的组件按窄屏/宽屏渲染。在 render 之前调。 */
|
||
export function setViewport(narrow: boolean) {
|
||
installMatchMedia(narrow);
|
||
}
|