测试组件
Modern.js 集成了 Jest,不需要做任何配置,可以直接给组件写测试用例。
我们执行 pnpm run new
开启测试功能:
# 启用可选功能
❯ 启用「单元测试 / 集成测试」功能
可以用以下两种方式给 Item 组件创建测试用例:
- macOS
- Windows
touch src/components/Item/index.test.tsx
ni src/components/Item/index.test.tsx
或
- macOS
- Windows
mkdir -p src/components/Item/__tests__/
touch src/components/Item/__tests__/index.tsx
mkdir -p src/components/Item/__tests__/
ni src/components/Item/__tests__/index.tsx
以前者为例,Item/index.test.tsx
的内容:
import { render } from '@modern-js/runtime/testing';
import Item from '.';
const defaultProps = {
info: {
avatar: 'https://via.placeholder.com/350x350',
name: 'foo',
email: 'foo.bar@bytedance.com',
archived: false,
},
};
describe('Item', () => {
it('should have contents', () => {
const {
info: { name },
} = defaultProps;
const { getByText } = render(<Item {...defaultProps} />);
expect(getByText(name)).toBeInTheDocument();
});
});
在之前章节创建的 modern-app-env.d.ts
文件 顶部(///
语法只在文件顶部生效) 加上类型定义:
/// <reference types="@modern-js/plugin-testing/type" />
注
更多相关内容可以查看 Test API。
执行 pnpm run test
,可以看到测试报告:
> modern test
PASS src/components/Item/index.test.tsx
Item
✓ should have contents (27 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.048 s, estimated 2 s
Ran all test suites.
本小节的代码可以在这里查看。