导入React组件时发生错误“目标容器不是DOM元素”

时间:2019-06-27 04:16:08

标签: javascript reactjs react-hooks react-testing-library

我想尝试测试react挂钩(在这种情况下,它还不是挂钩,我只是尝试将简单功能用作组件)。我有这个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中使用多次导入

1 个答案:

答案 0 :(得分:0)

我想您需要使用it而不是test here您可以结帐