File size: 10,408 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 |
import path from 'path';
import React from 'react';
// Reference: https://github.com/ant-design/ant-design/pull/24003#discussion_r427267386
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs';
import { extractStaticStyle } from 'antd-style';
import dayjs from 'dayjs';
import fse from 'fs-extra';
import { globSync } from 'glob';
import { JSDOM } from 'jsdom';
import MockDate from 'mockdate';
import type { HTTPRequest, Viewport } from 'puppeteer';
import rcWarning from 'rc-util/lib/warning';
import ReactDOMServer from 'react-dom/server';
import { App, ConfigProvider, theme } from '../../components';
import { fillWindowEnv } from '../setup';
import { render } from '../utils';
import { TriggerMockContext } from './demoTestContext';
jest.mock('../../components/grid/hooks/useBreakpoint', () => () => ({}));
const snapshotPath = path.join(process.cwd(), 'imageSnapshots');
fse.ensureDirSync(snapshotPath);
const themes = {
default: theme.defaultAlgorithm,
dark: theme.darkAlgorithm,
compact: theme.compactAlgorithm,
};
interface ImageTestOptions {
onlyViewport?: boolean;
ssr?: boolean | string[];
openTriggerClassName?: string;
mobile?: boolean;
}
// eslint-disable-next-line jest/no-export
export default function imageTest(
component: React.ReactElement,
identifier: string,
filename: string,
options: ImageTestOptions,
) {
let doc: Document;
let container: HTMLDivElement;
beforeAll(async () => {
const dom = new JSDOM('<!DOCTYPE html><body></body></html>', {
url: 'http://localhost/',
});
const win = dom.window;
doc = win.document;
(global as any).window = win;
// Fill env
const keys = [
...Object.keys(win),
'HTMLElement',
'SVGElement',
'ShadowRoot',
'Element',
'File',
'Blob',
].filter((key) => !(global as any)[key]);
keys.forEach((key) => {
(global as any)[key] = win[key];
});
// Fake Resize Observer
global.ResizeObserver = function FakeResizeObserver() {
return {
observe() {},
unobserve() {},
disconnect() {},
};
} as unknown as typeof ResizeObserver;
// Fake promise not called
global.fetch = function mockFetch() {
return {
then() {
return this;
},
catch() {
return this;
},
finally() {
return this;
},
};
} as unknown as typeof fetch;
// Fake matchMedia
win.matchMedia = (() => ({
matches: false,
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
})) as unknown as typeof matchMedia;
// Fill window
fillWindowEnv(win);
await page.setRequestInterception(true);
});
beforeEach(() => {
doc.body.innerHTML = `<div id="root"></div>`;
container = doc.querySelector<HTMLDivElement>('#root')!;
});
function test(name: string, suffix: string, themedComponent: React.ReactElement, mobile = false) {
it(name, async () => {
const sharedViewportConfig: Partial<Viewport> = {
isMobile: mobile,
hasTouch: mobile,
};
await page.setViewport({ width: 800, height: 600, ...sharedViewportConfig });
const onRequestHandle = (request: HTTPRequest) => {
if (['image'].includes(request.resourceType())) {
request.abort();
} else {
request.continue();
}
};
const { openTriggerClassName } = options;
const requestListener = (request: any) => onRequestHandle(request as HTTPRequest);
MockDate.set(dayjs('2016-11-22').valueOf());
page.on('request', requestListener);
await page.goto(`file://${process.cwd()}/tests/index.html`);
await page.addStyleTag({ path: `${process.cwd()}/components/style/reset.css` });
await page.addStyleTag({ content: '*{animation: none!important;}' });
const cache = createCache();
const emptyStyleHolder = doc.createElement('div');
let element = (
<StyleProvider cache={cache} container={emptyStyleHolder}>
<App>{themedComponent}</App>
</StyleProvider>
);
// Do inject open trigger
if (openTriggerClassName) {
element = (
<TriggerMockContext.Provider value={{ popupVisible: true }}>
{element}
</TriggerMockContext.Provider>
);
}
let html: string;
let styleStr: string;
if (
options.ssr &&
(options.ssr === true || options.ssr.some((demoName) => filename.includes(demoName)))
) {
html = ReactDOMServer.renderToString(element);
styleStr = extractStyle(cache) + extractStaticStyle(html).map((item) => item.tag);
} else {
const { unmount } = render(element, {
container,
});
html = container.innerHTML;
styleStr = extractStyle(cache) + extractStaticStyle(html).map((item) => item.tag);
// We should extract style before unmount
unmount();
}
// Remove mobile css for hardcode since CI will always think as mobile
if (!mobile) {
styleStr = styleStr.replace(/@media\(hover:\s*none\)/g, '@media(hover:not-valid)');
}
if (openTriggerClassName) {
styleStr += `<style>
.${openTriggerClassName} {
position: relative !important;
left: 0 !important;
top: 0 !important;
opacity: 1 !important;
display: inline-block !important;
vertical-align: top !important;
}
</style>`;
}
await page.evaluate(
(innerHTML: string, ssrStyle: string, triggerClassName?: string) => {
const root = document.querySelector<HTMLDivElement>('#root')!;
root.innerHTML = innerHTML;
const head = document.querySelector<HTMLElement>('head')!;
head.innerHTML += ssrStyle;
// Inject open trigger with block style
if (triggerClassName) {
document.querySelectorAll<HTMLElement>(`.${triggerClassName}`).forEach((node) => {
const blockStart = document.createElement('div');
const blockEnd = document.createElement('div');
node.parentNode?.insertBefore(blockStart, node);
node.parentNode?.insertBefore(blockEnd, node.nextSibling);
});
}
},
html,
styleStr,
openTriggerClassName || '',
);
if (!options.onlyViewport) {
// Get scroll height of the rendered page and set viewport
const bodyHeight = await page.evaluate(() => document.body.scrollHeight);
// loooooong image
rcWarning(
bodyHeight < 4096, // Expected height
`[IMAGE TEST] [${identifier}] may cause screenshots to be very long and unacceptable.
Please consider using \`onlyViewport: ["filename.tsx"]\`, read more: https://github.com/ant-design/ant-design/pull/52053`,
);
await page.setViewport({ width: 800, height: bodyHeight, ...sharedViewportConfig });
}
const image = await page.screenshot({
fullPage: !options.onlyViewport,
});
await fse.writeFile(path.join(snapshotPath, `${identifier}${suffix}.png`), image);
MockDate.reset();
page.off('request', requestListener);
});
}
if (!options.mobile) {
Object.entries(themes).forEach(([key, algorithm]) => {
const configTheme = {
algorithm,
token: {
fontFamily: 'Arial',
},
};
test(
`component image screenshot should correct ${key}`,
`.${key}`,
<div style={{ background: key === 'dark' ? '#000' : '', padding: `24px 12px` }} key={key}>
<ConfigProvider theme={configTheme}>{component}</ConfigProvider>
</div>,
);
test(
`[CSS Var] component image screenshot should correct ${key}`,
`.${key}.css-var`,
<div style={{ background: key === 'dark' ? '#000' : '', padding: `24px 12px` }} key={key}>
<ConfigProvider theme={{ ...configTheme, cssVar: true }}>{component}</ConfigProvider>
</div>,
);
});
// Mobile Snapshot
} else {
test(identifier, `.mobile`, component, true);
test(
identifier,
`.mobile.css-var`,
<ConfigProvider theme={{ cssVar: true }}>{component}</ConfigProvider>,
true,
);
}
}
type Options = {
skip?: boolean | string[];
onlyViewport?: boolean | string[];
/** Use SSR render instead. Only used when the third part deps component */
ssr?: boolean | string[];
/** Open Trigger to check the popup render */
openTriggerClassName?: string;
mobile?: string[];
};
// eslint-disable-next-line jest/no-export
export function imageDemoTest(component: string, options: Options = {}) {
let describeMethod = options.skip === true ? describe.skip : describe;
const files = globSync(`./components/${component}/demo/*.tsx`).filter(
(file) => !file.includes('_semantic'),
);
const mobileDemos: [file: string, node: any][] = [];
const getTestOption = (file: string) => ({
onlyViewport:
options.onlyViewport === true ||
(Array.isArray(options.onlyViewport) && options.onlyViewport.some((c) => file.endsWith(c))),
ssr: options.ssr,
openTriggerClassName: options.openTriggerClassName,
});
files.forEach((file) => {
if (Array.isArray(options.skip) && options.skip.some((c) => file.endsWith(c))) {
describeMethod = describe.skip;
} else {
describeMethod = describe;
}
describeMethod(`Test ${file} image`, () => {
let Demo = require(`../../${file}`).default;
if (typeof Demo === 'function') {
Demo = <Demo />;
}
imageTest(Demo, `${component}-${path.basename(file, '.tsx')}`, file, getTestOption(file));
// Check if need mobile test
if ((options.mobile || []).some((c) => file.endsWith(c))) {
mobileDemos.push([file, Demo]);
}
});
});
if (mobileDemos.length) {
describeMethod(`Test mobile image`, () => {
beforeAll(async () => {
await jestPuppeteer.resetPage();
});
mobileDemos.forEach(([file, Demo]) => {
imageTest(Demo, `${component}-${path.basename(file, '.tsx')}`, file, {
...getTestOption(file),
mobile: true,
});
});
});
}
}
|