期待JavaScript测试自动化课程的开始 ,我们将 继续发布一系列有用文章的翻译。
这是关于使用React进行测试的系列文章的第三部分。在最后一部分中,我们介绍了模拟React组件的基本格式。
模拟可以做的另一件事是检查是否传入了正确的子代。这实际上就是我们现在要看的内容。
此存储库中提供了本文的所有代码示例。
假设我们要在中插入新闻通讯订阅表单PostContent。我们可以通过让孩子们去做。
这是更新的组件BlogPage:
export const BlogPage = ({ url }) => {
const id = getPostIdFromUrl(url)
const handleSignUp = () => {
// …
}
return (
<PostContent id={id}>
<input type="email" placeholder="Sign up to my mailing list!" />
<button onClick={handleSignUp}>Sign up</button>
</PostContent>
)
}重要的是我们的测试BlogPage不应该关心它对 PostContent孩子的影响。他们只需要确保将其移交给他即可。
, children .mock.calls render. , .
- children:
jest.mock("../src/PostContent", () => ({
PostContent: jest.fn(({ children }) => (
<div data-testid="PostContent">{children}</div>
))
})) , , button PostContent:
it("renders the mailing list sign up button as a child of PostContent", () => {
render(<BlogPage url="http://example.com/blog/my-web-page" />)
const postContentElement = screen.getByTestId("PostContent")
const button = screen.queryByRole(
"button", { name: "Sign up" })
expect(postContentElement).toContainElement(button)
}) input.
, . , , . :
expect(PostContent).toHaveBeenCalledWith(
{ id: postId },
expect.anything()) , children, .
expect.objectContain.
expect.objectContain
! . .
children- : , , ID, -, .
content, expect.objectContain :
expect(PostContent).toHaveBeenCalledWith(
expect.objectContaining({ id: postId }),
expect.anything()), ?
, , `jest.fn (({children}) = {children})
toContainElementjest-dom, , .
expect.objectContain, .
Jest
clearMocks, , .
: