我需要模拟表单实例以进行测试
!form?.isFieldsTouched()
案例
请不要建议提供表格作为道具。
这是我的组件:
export const OCRActions = ({ isEditDisabled, set }: IOCRActionsProps) => {
const form = useFormInstance();
return (
<Item
noStyle
shouldUpdate
>
{() => (
<Group>
<Popconfirm
title={(
<div className='w-[200px]'>
Do you want to apply made changes?
Note that they may result in receipt reprocessing.
</div>
)}
okText='Yes'
cancelText='No'
placement='bottom'
onConfirm={handlePatchOCR(form, ocrFormValues, patchSnapsDetails)}
disabled={
!form?.isFieldsTouched()
}
>
<Button
type='primary'
loading={loading}
disabled={
!form?.isFieldsTouched()
}
>
Save
</Button>
</Popconfirm>
</Group>
)}
</Item>
);
};
我尝试过以这种方式进行模拟,但对我没有帮助,调用 useFormInstance() 返回未定义,我也使用了 GPT...
jest.mock('antd', () => {
const originalModule = jest.requireActual('antd');
return {
...originalModule,
Form: {
...originalModule.Form,
useFormInstance: jest.fn().mockReturnValueOnce({
getFieldsError: jest.fn().mockReturnValueOnce(() => []),
isFieldsTouched: jest.fn().mockReturnValueOnce(true),
}),
},
};
});
不要模拟
useFormInstance()
钩子,相反,您可以创建一个测试组件来渲染 <Form/>
组件和一个简单的 <Input/>
组件。更改输入的值,然后检查按钮是否被禁用。
例如
index.tsx
:
import React from 'react';
import { Button, Form } from 'antd';
const { useFormInstance, Item } = Form;
export const OCRActions = () => {
const form = useFormInstance();
return (
<Item noStyle shouldUpdate>
{() => (
<Button type="primary" disabled={!form?.isFieldsTouched()}>
Save
</Button>
)}
</Item>
);
};
index.test.tsx
:
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Form, Input } from 'antd';
import { OCRActions } from '.';
describe('78048690', () => {
test('should pass', () => {
const TestContainer = () => {
const [form] = Form.useForm();
return (
<Form form={form}>
<Form.Item name="username">
<Input placeholder="Username" />
</Form.Item>
<OCRActions />
</Form>
);
};
render(<TestContainer />);
const button = screen.getByRole('button');
expect(button).toBeDisabled();
fireEvent.change(screen.getByPlaceholderText('Username'), { target: { value: 'mrdulin' } });
expect(button).toBeEnabled();
});
});
测试结果:
PASS stackoverflow/78048690/index.test.tsx
78048690
√ should pass (290 ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.947 s, estimated 3 s
Ran all test suites related to changed files.
封装版本:
"react": "^18.2.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"@testing-library/jest-dom": "^6.1.4",
"@testing-library/react": "^14.1.2",
"antd": "^5.14.2",