reactjs - React Typescript 测试 - 目标容器不是 DOM 元素
问题描述
我是测试 React/Typescript 应用程序的新手。
命令(别名react-scripts test
):
yarn test
输出:
FAIL src/containers/pages/Feature/Feature.test.tsx
● Test suite failed to run
Target container is not a DOM element.
17 | const { store, persistor } = configureStore(history, initialState);
18 |
> 19 | ReactDOM.render(
| ^
20 | <Provider store={store}>
21 | <PersistGate loading={null} persistor={persistor}>
22 | <ConnectedRouter history={history}>
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:27596:13)
at Object.render (src/index.tsx:19:10)
简单的测试代码:
import * as React from 'react';
import { create } from 'react-test-renderer';
import Feature from "./Feature";
describe('Feature page component', () => {
test('matches the snapshot', () => {
const feature = create(
<Feature />,
);
expect(feature.toJSON()).toMatchSnapshot();
});
});
src/index.tsx 文件实际上包含ReactDOM.render()
在测试中失败的调用,但有什么可行的替代方法?
注意:应用程序本身运行良好,只是无法在测试模式下运行。
在 src/index.tsx 文件中我有:
export const history = createBrowserHistory({
basename: '/admin',
});
const initialState: StoreState = (undefined as unknown) as StoreState;
const { store, persistor } = configureStore(history, initialState);
然后在服务和传奇中,我history
从store
index.tsx 导入。可能是导致测试失败的问题吗?
我试图提取history
并保存store
到一个单独的文件中(如评论者所建议的那样)。现在上面的代码在里面src/initialState.ts
。
- 好消息:错误“目标容器不是 DOM 元素”消失了!
- 坏消息:我收到一个新错误(可能是一个独立的问题,因此提取到一个单独的问题)
解决方案
现在在您的测试中发生的问题是您想要测试一个从index.tsx
. 当您的 import fromindex.tsx
ReactDOM.render
也被调用并且您的测试失败时。
确保不要从
index.tsx
单独的文件中导入和移动您在那里定义的逻辑。
通常,您的应用程序会有一个索引文件,例如:index.tsx
它导入您的App.tsx
并且只关心将 React 组件渲染到带有ReactDOM.render
.
在中,App.tsx
您将定义所有组件,例如Provider
, PersistGate
, 甚至Feature
当你测试你的组件时,你要确保它不ReactDOM.render
包含ReactDOM.render
我提供了一个示例,说明如何在代码盒中设置类似的内容
现在我更喜欢使用@testing-library/react测试组件,而不是react-test-renderer
它也成为默认的测试库create-react-app
。
推荐阅读
- java - @BeforeAll 和 @Transaction 不起作用 - 数据库端的更改不会回滚
- amazon-web-services - AWS ECS 使用 CloudFormation 担任角色。在 ECS 中部署的 Docker 微服务在哪里获得假定角色?
- android - 如何查询where-greater-than然后按firestore中的另一个文档值对其进行排序?
- python - Oozie shell 动作创建 python 虚拟环境
- typescript - 当我知道 `this` 是动态的时,我可以使用 Typescript 强制使用经典函数作为参数而不是箭头函数吗?
- java - 如何使用java从字符位置获取文件中的行号
- javascript - 使用javascript循环更改单词最后一个字符的颜色
- vue.js - 如何将数组参数传递给 url VueJs
- mongodb - 有没有办法最小化 $graphlookup 输出?
- c# - Json 到 C# 类的转换