こんにちは、Habr。「JavaScriptでのテスト自動化」コースの学生募集を開始しました。この点に関して、「テスターがJSについて知っておくべきこと」というトピックに関する無料のデモレッスンに参加することをお勧めします。
そして今、私たちはあなたと一連の有用な翻訳の続きを共有しています。
React Testing Library (5 ):
React . . . : .
.
dirv / -react-
React .
TopFivePostsPage
, , , .
import { PostContent } from "./PostContent"
export const TopFivePostsPage = () => (
<ol>
<PostContent id="top1" />
<PostContent id="top2" />
<PostContent id="top3" />
<PostContent id="top4" />
<PostContent id="top5" />
</ol>
);
queryAllByTestId
toHaveLength
.
describe("BlogPage", () => {
it("renders five PostContent components", () => {
render(<TopFivePostsPage />)
expect(screen.queryAllByTestId("PostContent"))
.toHaveLength(5)
})
})
, , .
it("constructs a PostContent for each top 5 entry", () => {
render(<TopFivePostsPage />)
expect(PostContent).toHaveBeenCalledWith(
{ id: "top1" }, expect.anything())
expect(PostContent).toHaveBeenCalledWith(
{ id: "top2" }, expect.anything())
expect(PostContent).toHaveBeenCalledWith(
{ id: "top3" }, expect.anything())
expect(PostContent).toHaveBeenCalledWith(
{ id: "top4" }, expect.anything())
expect(PostContent).toHaveBeenCalledWith(
{ id: "top5" }, expect.anything())
})
- . . ToHaveBeenCalledWith
.
.mock.calls
.
it("renders PostContent items in the right order", () => {
render(<TopFivePostsPage />)
const postContentIds = PostContent.mock.calls.map(
args => args[0].id)
expect(postContentIds).toEqual([
"top1", "top2", "top3", "top4", "top5"
])
})
TopFivePostsPage
, , PostContent
! - , .
, clearMocks
Jest. package.json
.
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
},
"setupFilesAfterEnv": ["./jest.setup.js"],
"clearMocks": true
}
, , , .
:
, . , , . , .
jest.mock("../src/PostContent", () => ({
PostContent: jest.fn(({ children, id }) => (
<div data-testid={`PostContent-${id}`}>
{children}
</div>
))
}))
. , , . , .
, , , — , . , , . .
?
queryAllByTestId
.
.mock.calls
.
Jest's
clearMocks
, , .
, ,
data-testid
.
, !
. , , .
React . , , .
.
dirv / -react-
, React .
— . .
, .
, ? : !
, , .
jest.mock("../src/PostContent", () => ({
PostContent: jest.fn(() => (
<div data-testid="PostContent" />
))
}))
jest.mock("../src/PostContent", () => ({
PostContent: jest.fn(({ children }) => (
<div data-testid="PostContent">{children}</div>
))
}))
, , data-testids
. . .
jest.mock("../src/PostContent", () => ({
PostContent: jest.fn(({ children, id }) => <div data-testid={`PostContent-${id}`}>{children}</div>)
}))
, : . -, , , , , Jest mockImplementation
.
? , , , .
. , .
, , : , . , .
, ?
, , : ?
, , .
, React, , . , , .
.
? : , 100 . 10 !
, , ? : .
, «» , . «» — .
, , , React, , React.
?
React . , " , React ". React Testing Library, . , React .
« JavaScript».
« JS ».
