我正在为我的组件之一编写测试用例,其中包括一些文本输入以及一些上传文档部分。我正在为这个组件编写测试用例而苦苦挣扎。
这是我的
test.tsx
文件的代码:
it("calls create endpoint", async () => {
const createRequest = mockEndpointOnce(
ProductCatalogueAdminService,
"postV1AdminCatalogueProvider",
{},
)
const { gstore } = render(<ModalFragment />)
gstore.modals.open(() => <ProviderDetailModal />)
await screen.findByText("provider-detail-modal.settings-section.header")
const providerName = await screen.findByPlaceholderText(
"provider-detail-modal.settings-section.provider-name-placeholder",
)
userEvent.paste(providerName, "test")
const contactDetails = await screen.findByPlaceholderText(
"provider-detail-modal.settings-section.contact-details-placeholder",
)
userEvent.paste(contactDetails, "[email protected]")
const handleChange = jest.fn()
render(
<UploadDocumentField
onChange={handleChange}
max={1}
disabled={false}
/>,
)
const input = await screen.findByTestId("UploadDocumentField/Input")
const file = new File([], "test.pdf")
userEvent.upload(input, file)
expect(handleChange).toHaveBeenCalledWith(
[],
[expect.objectContaining({ file })],
"document",
)
const orderOutputName = await screen.findByPlaceholderText(
"provider-detail-modal.order-output-section.order-output-name-placeholder",
)
userEvent.paste(orderOutputName, "orderOutputName")
const orderOutputEmail = await screen.findByPlaceholderText(
"provider-detail-modal.order-output-section.order-output-email-placeholder",
)
userEvent.paste(orderOutputEmail, "[email protected]")
const saveButton = screen.getByText("provider-detail-modal.save-button")
userEvent.click(saveButton)
await delay(500)
expect(createRequest).toHaveBeenCalledTimes(1)
})
这里是我的组件的返回方法代码:
return (
<Form onSubmit={handleSubmit}>
<ModalHeader>
<Button
type="submit"
variant="contained"
disabled={gstore.loading.is(
ProviderDetailStore.LoadingKeys.submit,
)}
>{t`provider-detail-modal.save-button`}</Button>
</ModalHeader>
{Boolean(store.fields.error("generic")) && (
<Alert severity="error">{store.fields.error("generic")}</Alert>
)}
<FormPanel
sections={[
{
header: t`provider-detail-modal.settings-section.header`,
content: (
<>
<FormFieldSet
header={t`provider-detail-modal.terms-and-condition-attachments.header`}
tooltip={t`provider-detail-modal.terms-and-condition-attachments.tooltip`}
>
<DocumentAttachments
value={store.fields.get(
"termsAndConditionAttachments",
)}
onChange={(documents) => {
store.fields.set(
"termsAndConditionAttachments",
documents,
)
}}
max={1}
/>
<SpanContainer>
{store.fields.error(
"termsAndConditionAttachments",
)}
</SpanContainer>
</FormFieldSet>
<FormFieldSet
header={t`provider-detail-modal.privacy-policy-attachments.header`}
tooltip={t`provider-detail-modal.privacy-policy-attachments.tooltip`}
>
<DocumentAttachments
value={store.fields.get(
"privacyPolicyAttachments",
)}
onChange={(documents) => {
store.fields.set(
"privacyPolicyAttachments",
documents,
)
}}
max={1}
/>
<SpanContainer>
{store.fields.error(
"privacyPolicyAttachments",
)}
</SpanContainer>
</FormFieldSet>
</>
),
},
]}
/>
</Form>
)
在提交按钮内,我设置了一个验证条件,其方法定义为:
private validate() {
if (this.fields.get("termsAndConditionAttachments").length === 0) {
this.fields.setError(
"termsAndConditionAttachments",
t`errors.required`,
)
}
if (this.fields.get("privacyPolicyAttachments").length === 0) {
this.fields.setError("privacyPolicyAttachments", t`errors.required`)
}
}
在
DocumentAttachments
组件中有一个名为 UploadDocumentField
的组件,它实际上执行 pdf 上传内容并在 formfield 中返回上传的 URL。
UploadDocumentField
的代码如下:
export const DocumentAttachments = observer((props: IProps) => {
const handleChange = useCallback(
(files: IFile[]) => {
props.onChange([...props.value, ...files])
},
[props],
)
const removeAtIndex = useCallback(
(index: number) => {
const value = props.value.slice(0)
value.splice(index, 1)
props.onChange(value)
},
[props],
)
return (
<Stack
component="ul"
sx={{ listStyle: "none", margin: 0, padding: 0 }}
spacing={2}
>
<li>
<UploadDocumentField
onChange={handleChange}
disabled={
props.readOnly === true ||
props.value.length >= props.max
}
max={props.max}
/>
</li>
{props.value.slice(0, props.max).map((file, i) => (
<li key={file.url}>
<Document
file={file}
onRemove={() => removeAtIndex(i)}
disabled={props.readOnly}
/>
</li>
))}
</Stack>
)
})
这里是测试用例的失败响应:
FAIL src/__tests__/modals/provider-detail/index.test.tsx
> ProviderDetailModal
> ✓ renders (154 ms)
> ✕ calls create endpoint (1276 ms)
> ✓ calls update endpoint (144 ms)
>
> ● ProviderDetailModal › calls create endpoint
>
> Found multiple elements by: [data-testid="UploadDocumentField/Input"]
>
> const input = await screen.findByTestId("UploadDocumentField/Input")
> | ^
> 52 | const file = new File([], "test.pdf")
> 53 |
> 54 | userEvent.upload(input, file)
>
> at waitForWrapper (node_modules/@testing-library/dom/dist/wait-for.js:187:27)
> at findByTestId (node_modules/@testing-library/dom/dist/query-helpers.js:101:12)
> at Object.<anonymous> (src/__tests__/modals/provider-detail/index.test.tsx:51:36)
>
> Test Suites: 1 failed, 1 total Tests: 1 failed, 2 passed, 3
> total Snapshots: 0 total Time: 4.863 s, estimated 5 s