起步
"@testing-library/jest-dom": "^5.16.2",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",
1
2
3
npm install --save-dev jest
1
测试普通函数
import React from "react";
describe("test", () => {
test("equal", () => {
expect(<div />).toEqual(<div />);
});
});
1
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
test("test1", () => {
expect(1).toBe(1)
});
1
2
3
it("test1", () => {
expect(1).toBe(1)
});
1
2
3
- 预期,结合结合
- 普通值对比:
预期(1).等于(1)
expect({name: "hdy"}).toEqual({name: "hdy"})
1
test("onClick", () => {
const fn = jest.fn()
const btn = <button onClick={fn}>button</button>
expect(fn).toBeCalled()
});
1
2
3
4
5
6
test("test1", () => {
expect(1 > 3).toBeFalsy();
});
test("test1", () => {
expect(1 === 1).toBeTruthy();
});
1
2
3
4
5
6
7
test("test1", () => {
expect(Math.random()).not.toBe(2);
});
1
2
3
渲染测试
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
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
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