在我的项目中,我很难让react-hooks库与Formik一起工作,特别是useFormikContext<FormTypeFields>()
。我有一些字段,我想测试在react-testing-library中自动输入的能力。现在我想我已经找到了一些东西,但是act函数中的result.current
是未定义的。我附上了示例代码,希望能有所帮助。
- TestForm. tsx *
import React from "react";
import { Grid, GridItem } from "@chakra-ui/react";
import { FormTypeFields } from "./form-type-fields.model";
const TestForm = () => {
const { values } = useFormikContext<FormTypeFields>();
const { testField } = values;
return (
<Grid
templateColumns="repeat(12, minmax(0, 1fr))"
gap={{ base: 6, md: 8, lg: 8 }}
>
<GridItem colSpan={12}>
<label for="testField">Test Field</label>
<input type="text" id="testField" name="testField" />
</GridItem>
</Grid>
);
}
export default TestForm;
- form-type-fields. model *
export class FormTypeFields {
testField: string = "";
constructor(entity: any) {
if (!entity) return;
this.testField = entity.testField;
}
}
下面是我尝试编写的测试:* TestForm. test. tsx *
import React from "react";
import { render } from "@testing-library/react";
import TestForm from "./TestForm";
import * as Formik from "formik";
import userEvent from "@testing-library/user-event";
import { renderHook, act } from "@testing-library/react-hooks";
import { FormTypeFields } from "./test-form-fields.model";
describe("typing should work", async () => {
const { result } = renderHook<
Formik.FormikContextType<FormTypeFields>,
Formik.FormikContextType<FormTypeFields>
>(() => Formik.useFormikContext<FormTypeFields>());
act(() => {
result.current.values = { testField: "" };
});
render(<TestForm />);
expect(screen).toMatchSnapshot();
await userEvent.keyboard("ABC");
expect(screen.getByLabelText("Test Field").innerHTML).toContain("ABC");
});
我不知道如何将其连接起来,以便在输入表单上的react-testing-library功能中测试keyboard("ABC")
函数。
错误消息如下:
TypeError: Cannot set properties of undefined (setting 'values')
15 |
16 | act(() => {
> 17 | result.current.values = { testField: "" };
| ^
18 | });
19 |
20 | render(<TestForm />);
我得到了这样的警告:
console.warn
Warning: Formik context is undefined, please verify you are calling useFormikContext() as child of
a <Formik> component.
11 | Formik.FormikContextType<FormTypeFields>,
12 | Formik.FormikContextType<FormTypeFields>
> 13 | >(() => Formik.useFormikContext<FormTypeFields>());
| ^
14 |
15 | act(() => {
16 | result.current.values = { testField: "" };
寻求建议,谢谢。
1条答案
按热度按时间fzsnzjdm1#
我想出了答案。您所需要做的就是在渲染器中添加FormikProvider和Formik标记。