Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Testing a Typescript React Component Giving Error on getByText

I’m trying to add unit testing to an application written with Typescript and React. I have a very basic component just for the sake of simplicity.

import React from "react";
import ReactDOM from "react-dom";

type TypeProps = { }
type TypeState = { }

class App extends React.Component<TypeProps, TypeState> {
    constructor(props:TypeProps) {
        super(props);
        this.state = { };
    }
    render() {
        return(<p>Literally Nothing</p>);
    }
}

function renderApp() {
    let AppElement = document.getElementById("app");
    if(AppElement) { ReactDOM.render(<App />, AppElement); }
}

renderApp();
export { renderApp }

Then installed what I believed to be everything required for the tests

npm install --save-dev jest ts-jest @types/jest
npm install --save-dev @testing-library/jest-dom @testing-library/react

With jest.config.json as

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom'
};

So this is all fine and I have a unit test of nothing

import React from "react";
import ReactDOM from "react-dom";
import "@testing-library/jest-dom";
import { render } from "@testing-library/react";

import { renderApp } from "./App";

test("Literally Nothing", function() {
    renderApp();
    expect(getByText("App")).toBeInTheDocument();
});

But it is throwing the following error on build and npm run test

TS2304: Cannot find name 'getByText'.

Am I missing an install or configuration step?

>Solution :

You are missing getByText which is not imported anywhere.
I’d suggest you import screen

import { screen } from '@testing-library/react';
//....
renderApp();
const appText = screen.getByText("App");
expect(appText).toBeInTheDocument();

Also this will always assets false, because on your component there isn’t any text with the value "App", the onlye text that will render is "Literally Nothing".

So like this will work:

const appText = screen.getByText("Literally Nothing");
expect(appText).toBeInTheDocument();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading