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
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?
CodePudding user response:
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();