استعدادًا لبدء دورة JavaScript Test Automation ، نواصل نشر ترجمة سلسلة من المقالات المفيدة.
هذا هو الجزء الثالث في سلسلة حول الاختبار باستخدام React. في الجزء الأخير ، غطينا التنسيق الأساسي للاستهزاء بمكونات React .
شيء آخر يمكنك القيام به مع mocks هو التحقق مما إذا كان قد تم تمرير الأطفال المناسبين. هذا في الواقع ما سننظر إليه الآن.
تتوفر جميع نماذج التعليمات البرمجية لهذه المقالة في هذا المستودع.
تخيل أننا نريد إدخال نموذج اشتراك في رسالة إخبارية بالداخل 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, , .
: