# 起步
- api 文档 (opens new window)
- create-react-app自带单测
"@testing-library/jest-dom": "^5.16.2",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
1
2
3
2
3
- 安装
npm install --save-dev jest
1
- 启动
npm run test
1
# 测试普通函数
- 定义测试代码块,并且可以分组/嵌套
// tests/index.test.js
import React from "react";
describe("test", () => {
test("equal", () => {
expect(<div />).toEqual(<div />);
});
});
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 嵌套多组测试
import React from "react";
describe("test", () => {
test("test1", () => {
expect(1).toBe(1)
});
describe("group", () => {
test("test1", () => {
expect(1).toBe(1)
});
test("test2", () => {
expect(2).toBe(2)
});
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- 同
it
test("test1", () => {
expect(1).toBe(1)
});
1
2
3
2
3
it("test1", () => {
expect(1).toBe(1)
});
1
2
3
2
3
- 预期,结合结合
- 普通值对比:
预期(1).等于(1)
expect(1).toBe(1)
1
- 对象等引用相等
expect({name: "hdy"}).toEqual({name: "hdy"})
1
test("onClick", () => {
const fn = jest.fn()
const btn = <button onClick={fn}>button</button>
// 点击btn
expect(fn).toBeCalled()
});
1
2
3
4
5
6
2
3
4
5
6
- 真/假
test("test1", () => {
expect(1 > 3).toBeFalsy();
});
test("test1", () => {
expect(1 === 1).toBeTruthy();
});
1
2
3
4
5
6
7
2
3
4
5
6
7
test("test1", () => {
expect(Math.random()).not.toBe(2);
});
1
2
3
2
3
# 渲染测试
- react18会有render提示,无视就行
import React from 'react'
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
test("1", () => {
const {asFragment} = render(<div>Foo</div>);
expect(screen.getByText('Foo')).toBeInTheDocument()
expect(asFragment()).toMatchInlineSnapshot(`
<DocumentFragment>
<div>
Foo
</div>
</DocumentFragment>
`)
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- 渲染指定组件,包含字段
import React from 'react'
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
test('has correct welcome text', () => {
render(<div>hello world!</div>)
expect(screen.getByText(/hello/i)).toHaveTextContent('hello world')
})
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 使用正则
import React from 'react'
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
test('has correct welcome text', () => {
render(
<div>
hello
<div><div>hello world!</div></div>
</div>
)
expect(screen.getByText(/hello world!/)).toBeInTheDocument()
})
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13