In anticipation of the start of the JavaScript Test Automation course , we continue to publish the translation of a series of useful articles.
This is the third part in a series about testing with React. In the last part, we covered the basic format for mocking React components .
Another thing you can do with mocks is to check if the correct children were passed in. That's actually what we'll look at now.
All code samples for this article are available in this repository.
Imagine we want to insert a newsletter subscription form inside PostContent
. We can do this by passing children to it.
Here's the updated component 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>
)
}
The important thing is that our tests BlogPage
shouldn't care what it PostContent
does to the children. They just have to make sure they are passed on to him.
, 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})
toContainElement
jest-dom
, , .
expect.objectContain
, .
Jest
clearMocks
, , .
: