首页 > 解决方案 > TypeError:无法读取未定义 Jest 的属性“parentNode”

问题描述

我在我的项目中使用 react-testing-library 和 jest。我是这方面的新手。我试图对我的组件进行一些测试,但我遇到了错误。我知道我需要通过道具来测试哪个使用我的组件,但我不知道如何。

这是我的主要组成部分:

组件A.tsx:

export const ComponentA: FC = () => {
    const [active, setActiveItem] = useState("");

    return (
            <div className="right-menu">
              <ComponentB onMouseEnter={() => setActiveItem("componentB")} />
            </div>
    );
  });

这是 ComponentB.tsx:

export const ComponentB: FC<CompProps> = ({ onMouseEnter }) => {
  return (
    <div onMouseEnter={onMouseEnter}>
      <img src={icon} alt="Some Image". data-testid="comp-b" />
    </div>
  );
};

这是我在 componentB 上使用的 CompProps:

type CompProps = {
  onMouseEnter?: () => void;
};

所以我不想测试我的 ComponentB:这是我的 ComponentB 测试文件:

import React from "react";
import { ComponentB as Component } from "./";
import { render } from "@testing-library/react";

it("renders without crashing", async () => {
  const wrapper = render(
      <Component onMouseEnter={() => {}} />
  );
  expect(wrapper).toMatchSnapshot();
  wrapper.unmount();
});

并在这里显示错误:TypeError: Cannot read property 'parentNode' of undefinedJest

这是什么意思以及如何解决这个问题?

标签: reactjstypescriptjestjsreact-testing-library

解决方案


推荐阅读