UNPKG

rerumaccusamus

Version:

The meta-framework suite designed from scratch for frontend-focused modern web development.

114 lines (82 loc) 2.48 kB
--- title: ​测试组件​​​ --- Modern.js 集成了 [Jest](https://jestjs.io/),不需要做任何配置,可以直接给组件写测试用例。 我们执行 `pnpm run new` 开启测试功能: ```bash # 启用可选功能 ❯ 启用「单元测试 / 集成测试」功能 ``` 可以用以下两种方式给 Item 组件创建测试用例: import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; <Tabs> <TabItem value="macOS" label="macOS" default> ```bash touch src/components/Item/index.test.tsx ``` </TabItem> <TabItem value="Windows" label="Windows"> ```powershell ni src/components/Item/index.test.tsx ``` </TabItem> </Tabs> 或 <Tabs> <TabItem value="macOS" label="macOS" default> ```bash mkdir -p src/components/Item/__tests__/ touch src/components/Item/__tests__/index.tsx ``` </TabItem> <TabItem value="Windows" label="Windows"> ```powershell mkdir -p src/components/Item/__tests__/ ni src/components/Item/__tests__/index.tsx ``` </TabItem> </Tabs> 以前者为例,`Item/index.test.tsx` 的内容: ```js 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` 文件 **顶部**([`///` 语法只在文件顶部生效](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#:~:text=Triple-slash%20directives%20are%20only%20valid%20at%20the%20top%20of%20their%20containing%20file.)) 加上类型定义: ```ts /// <reference types="@modern-js/plugin-testing/type" /> ``` :::note 注 更多相关内容可以查看 [Test API](/docs/apis/runtime/testing/render)。 ::: 执行 `pnpm run test`,可以看到测试报告: ```bash > 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. ``` --- > 本小节的代码可以在[这里查看](https://github.com/modern-js-dev/modern-js-examples/tree/main/tutorials/c06/hello-modern-6)。