我们如何测试数百个着陆页
最后的考虑
自动化测试是确保软件质量和提供良好用户体验的绝佳方法。在 Woovi,我们有数千个落地页,有时用户第一次接触我们,是通过这些展示我们产品的页面。因此,我们需要确保每个页面都能正常运行。每个访问我们页面的用户都代表着一个新的客户获取机会。
测试登陆页面的挑战
Woovi 的落地页仅呈现静态内容,例如文本、图片以及用于重定向到其他页面的按钮。由于其简洁性,无需为每个新页面创建专门的测试,因为它们没有需要更复杂测试的高级业务规则。每个新页面都会显示不同的内容,因此我们需要简化测试流程。手动测试每个页面是不可行的。千万不要这样做!
解决方案:渲染测试
我们结合使用渲染测试(来自测试库的渲染测试)和glob库来确保所有页面都经过有效测试。
- 渲染测试:用于检查组件或页面是否正确渲染且无错误。它还能确保渲染后用户界面中显示预期元素。
- GlobSync:用于同步搜索与特定模式匹配的文件和目录(在本例中为 .tsx)。这意味着该函数执行搜索并立即返回结果,并阻止执行,直到操作完成。
按如下方式组织您的项目:
src/
│
├── __tests__/
│ └── renderScreens.spec.tsx # Render test file for pages
│
├── pages/ # Directory containing the pages to be tested
│ ├── Home.tsx # Example page: Home
│ ├── About.tsx # Example page: About
│ ├── Contact.tsx # Example page: Contact
│ └── ... # Other project pages
来源:
import { globSync } from 'glob';
import { render } from '@testing-library/react';
import path from 'path';
const screensPath = path.resolve(__dirname, '../pages');
const screensPattern = `${screensPath}/**/*.tsx`;
const screensIgnorePattern = '**/_*.tsx';
const getScreens = () => {
try {
const screenFiles = globSync(screensPattern, {
ignore: [screensIgnorePattern],
});
return screenFiles.map((filePath) => {
const relativePath = path.relative(screensPath, filePath);
const component = require(filePath).default;
return {
name: relativePath,
component,
};
});
} catch (e) {
console.log('Error fetching files:', e);
return [];
}
};
const screens = getScreens();
test.each(screens.map(({ name, component: Screen }) => [name, Screen]))(
'Render screen: %s',
(_, Screen) => {
render(<Screen />);
},
);
输出:
代码解释
- getScreens():此函数使用 globSync 同步搜索 /pages 目录及其子目录中的所有 .tsx 文件。它返回一个对象列表,每个对象包含文件名和相应的组件。
- screens:存储 getScreens 函数结果的常量,包含所有将要测试的页面。
- test.each():该方法为每个页面运行渲染测试。它将页面名称和组件传递给测试函数,以确保所有页面都能正确渲染。
最后的考虑
这种自动化测试方法可确保所有落地页均正确呈现,无需为每个页面单独创建测试。这不仅节省了时间和资源,还能确保用户在访问您的页面时获得一致的体验。
使用本文作为基础,使测试适应您的项目需求,并始终仔细测试实施情况。
鏂囩珷鏉ユ簮锛�https://dev.to/woovi/how-did-we-test-hundreds-of-landing-pages-3nj9