![](/img/trans.png)
[英]React native typeScript and forwardRef in a functional component
[英]ForwardRef component error: jest react native
我正在尝试为我的帖子详细信息屏幕编写测试用例,但在运行它时出现错误提示:
error occurred in the <ForwardRef> component:
我的测试class:
import React from "react";
import { NewPostScreenTemplate } from "../screens/NewPost/template";
import renderer from "react-test-renderer";
import {
tenantInfo,
imageLayout1,
imageLayout2,
imageLayout3,
communityCategories,
} from "../mocks/NewPostScreenMock";
import { Provider } from "react-redux";
import { createStore } from "redux";
jest.useFakeTimers();
describe("Community New Post Screen", () => {
const mockReducer = () => ({
customerInfo: { tenantsInfo: tenantInfo },
community: {
communityCategory: communityCategories,
selectedFiles: [],
shouldShowImageCountWarningBox: false,
shouldShowImageSizeWarningBox: false,
},
});
const mockStore = createStore(mockReducer);
const childRef = jest.spyOn(React, "useRef").mockReturnValueOnce({ current: null });
test("Simple new post screen", () => {
const communityNewPost = renderer
.create(
<Provider store={mockStore}>
<NewPostScreenTemplate
ref={childRef}
tenantInfo={tenantInfo}
handleOnPublish={jest.fn}
communityCategories={communityCategories}
onBackPress={jest.fn}
selectedImageFile={[]}
showCameraPicker={jest.fn}
showGalleryPicker={jest.fn}
shouldShowImageSizeWarningBox={false}
shouldShowImageCountWarningBox={false}
/>
</Provider>
)
.toJSON();
expect(communityNewPost).toMatchSnapshot();
});
请指导我如何为这个组件编写测试。 我在编写测试用例时犯了什么错误。
我什至尝试使用以下代码:
jest.mock("../screens/NewPost/template", () => {
const { forwardRef } = jest.requireActual("react");
return {
__esModule: true,
default: forwardRef((props, ref) => <div ref={ref} />),
};
});
但这会引发错误:
元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件)但得到:未定义。 您可能忘记从定义它的文件中导出您的组件,或者您可能混淆了默认导入和命名导入。
谢谢
这是我为解决此问题所做的工作:
只需添加此 function:
jest.mock("react", () => {
const originReact = jest.requireActual("react");
const mUseRef = jest.fn();
return {
...originReact,
useRef: mUseRef,
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.