Home > Mobile >  React unit test getting TypeError: Cannot read properties of undefined (reading 'Component'
React unit test getting TypeError: Cannot read properties of undefined (reading 'Component'

Time:06-22

I'm new to React and React unit testing. I'm trying to create a simple test and am getting the following error: "TypeError: Cannot read properties of undefined (reading 'Component')" Here's my code.

HelloWorld.js

import React from "react";

class HelloWorld extends Component {
  render() {
    return ( < h1 > My First ReactJS Core App! < /h1>);
    }
  }
  export default HelloWorld

test.js

import React from "react";
import {
  HelloWorld
} from "../wwwroot/src/react/HelloWorld"
import {
  render,
  screen
} from "@testing-library/react";

describe("apptest", () => {
  it("works", () => {
    render( < HelloWorld / > );
    screen.getByText("My First ReactJS Core App!");
  });
});

When I run "npm test", I get the following:

enter image description here

What am I doing wrong?

CodePudding user response:

When I see your code, you don't have Component importing, but the error message shows React.Component. Does your original code match with your attached code?

If it is, please try to add the following import.

import React, {Component} from 'react'

CodePudding user response:

check this

import React, { Component } from "react";

class Temp extends Component {
  render() {
    return <h1> My First ReactJS Core App! </h1>;
  }
}
export default Temp;


import { render, screen } from "@testing-library/react";
import Temp from "./Temp";

describe("apptest", () => {
  it("works", () => {
    render(<Temp />);
    screen.getByText("My First ReactJS Core App!");
  });
});
  • Related