[英]Jest test fails on a react component which uses react-hooks-form with sharing refs
Here is the abstract version of my component这是我的组件的抽象版本
const Test = () => {
const { register } = useFormContext();
const mRef = useThirdpartyHook(); // Third party hook returns a ref
const { ref, ...rest } = register('test');
return (
<input
type="text"
name="test"
{...rest}
ref={(e) => {
ref(e);
mRef.current = e;
}}
/>
);
};
export default Test;
Test case测试用例
import React from 'react';
import { render } from '@testing-library/react';
import { FormProvider } from 'react-hook-form';
import Test from './Test';
describe('<Test> component', () => {
it('renders default correctly', () => {
const wrapper = render(
<FormProvider
{...{ register: () => jest.fn() }}>
<Test />
</FormProvider>
);
expect(wrapper.baseElement).toMatchSnapshot();
});
});
Executing this test throws an error as given below.执行这个测试会抛出一个错误,如下所示。
<Test> component › renders default correctly
TypeError: ref is not a function
ref={(e) => {
ref(e);
^
mRef.current = e;
}}
I tried to mock the ref as function but it didn't help.我试图将 ref 模拟为 function 但它没有帮助。 It would be great if anyone can throw some insights.如果有人能提出一些见解,那就太好了。
register
is a function that returns props the input needs. register
是一个 function 返回输入需要的道具。 You are mocking the register
function, but it still needs to return everything the component is consuming or passing on.你是 mocking register
function,但它仍然需要返回组件正在消耗或传递的所有内容。 Specifically it seems you need to return a ref
function for what is returned by the useFormContext
hook.具体来说,您似乎需要为useFormContext
挂钩返回的内容返回一个ref
function。
Example:例子:
describe('<Test> component', () => {
it('renders default correctly', () => {
const registerMock = () => ({
ref: jest.fn(),
.... mock other necessary bits here
});
const wrapper = render(
<FormProvider
{...{ register: registerMock }}
>
<Test />
</FormProvider>
);
expect(wrapper.baseElement).toMatchSnapshot();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.