简体   繁体   English

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

[英]Error 'Target container is not a DOM element' importing react component

I want to try to test react hook (in this case it isn't hook yet, I just tried simple function as component). 我想尝试测试react挂钩(在这种情况下,它还不是挂钩,我只是尝试将简单功能用作组件)。 I have this index.js 我有这个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;

The app run well, then I add this index.spec.js 该应用程序运行良好,然后添加了这个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);
});

Then I got error of 然后我得到了错误

Invariant Violation: Target container is not a DOM element.

What's wrong? 怎么了?

Update: 更新:

I separated Counter into another file, it worked, I wonder why I can't use multiple import in App.js 我将Counter分离到另一个文件中,它起作用了,我想知道为什么我不能在App.js中使用多个导入

我想您需要使用it而不是在这里进行test才能结帐

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM