【发布时间】:2019-06-27 04:16:08
【问题描述】:
我想尝试测试反应钩子(在这种情况下它还不是钩子,我只是尝试了简单的函数作为组件)。我有这个 index.js
import React, { useState } from "react";
export const Counter = () => {
const [count, setCount] = useState(0);
function increaseCount() {
setCount(count => count + 1);
}
return (
<div>
<h1 data-count>count: {count}</h1>
<button onClick={increaseCount}>increase</button>
</div>
);
};
function App() {
return (
<div className="App">
<Counter />
</div>
);
}
export default App;
应用运行良好,然后我添加这个 index.spec.js
import React from "react";
import { render, fireEvent } from "@testing-library/react";
import { Counter } from "./index"; //this line caused problem
test("Test", () => {
console.log("Counter", Counter);
});
然后我得到了错误
Invariant Violation: Target container is not a DOM element.
怎么了?
更新:
我将 Counter 分离到另一个文件中,它起作用了,我想知道为什么我不能在 App.js 中使用多个导入
【问题讨论】:
-
您可以从 App.js 进行多个导出。您的问题可能在其他地方。我看到您是从
./index导入的,而不是 App。是否有可能在index中渲染 App? -
@Gpx 不,当我将 Counter 函数移动到新文件时,问题得到了解决,这让我很惊讶。
标签: javascript reactjs react-hooks react-testing-library