Files
MailUI4Agents/client/electron/test/components/setup.ts

46 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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);
}