Rsbuild 本身不内置测试框架,它可以与各种流行的测试工具配合使用。
本指南将介绍如何在 Rsbuild 应用中添加 单元测试 和 端到端测试。
单元测试用于测试独立的组件和函数。Rsbuild 可以与 Rstest、Vitest、Jest 等测试框架配合使用。
下面以 Rstest 为例,介绍如何在 Rsbuild 应用中添加单元测试。
Rstest 基于 Rsbuild 实现的测试框架,为 Rsbuild 应用提供了一流的支持。它提供与 Jest 兼容的 API,同时原生支持 TypeScript、ESM 等现代特性。
npm add @rstest/core -D
在 package.json
中添加测试脚本:
{
"scripts": {
"test": "rstest",
"test:watch": "rstest -w"
}
}
创建测试文件,例如:
export function add(a: number, b: number) {
return a + b;
}
import { expect, test } from '@rstest/core';
import { add } from './utils';
test('should add two numbers correctly', () => {
expect(add(1, 2)).toBe(3);
expect(add(-1, 1)).toBe(0);
});
# 运行测试
npm run test
# 运行并监听
npm run test:watch
以上就是使用 Rstest 的基本步骤,查看 Rstest 文档 了解更多用法。
参考以下示例了解更多用法:
端到端测试用于测试完整的用户流程,确保应用在真实浏览器环境中正常工作。
你可以使用 Playwright 进行 E2E 测试,它是一个现代的端到端测试框架,详见 Playwright 文档。