【问题标题】:Error 'Target container is not a DOM element' importing react component导入反应组件时出现错误“目标容器不是 DOM 元素”
【发布时间】: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


【解决方案1】:

我猜你需要使用it 而不是test here可以结账

【讨论】:

  • 不。那不是问题。我把Counter函数单独作为一个文件,问题消失了,我不知道为什么我不能将它导出为App.js中的对象。
  • ittest 的别名,你可以使用你喜欢的那个
猜你喜欢
  • 1970-01-01
  • 2017-11-24
  • 1970-01-01
  • 2021-06-02
  • 2019-07-06
  • 1970-01-01
  • 2022-10-09
  • 2023-03-15
  • 2021-06-17
相关资源
最近更新 更多