Adding this question because I didn't easily find the answer online.
I am trying to use react-testing-library to test that a component renders correctly. However I get numerous errors that don't seem to help much.
Here is my test file (report.test.ts, alongside the component in the code):
import { render } from "react-testing-library";
import "jest-dom/extend-expect";
import Report from "./Report";
test("component", () => {
const reportData = {
name: "test-report-name",
url: "test-url"
};
const { getByText } = render(<Report report={reportData} />);
expect(getByText("test-report-name")).toHaveAttribute("href", "test-url");
});
When I try to run the test, I get the error SyntaxError: Unexpected token, expected "</>". There is a red squiggly line in VS Code that on hover says Argument of type 'Report' is not assignable to parameter of type 'ReactElement<any>'.
Even if I change the Report tag to be simply <div />, then I get Cannot find name 'div'.
What is the problem with my test?
The test file extension should be recognised as a file that uses the React syntax (eg. tsx), and React should be defined using import React from "react";.
When using the JSX syntax, it seems React must be defined in the file, and also the file type must be recognised as one that uses React. So presumably a similar change would be required if the test file had the js extension.
Here's the problem: whenever you type <div>Foo</div>, <Component /> or other JSX syntax that's not standard JavaScript. If you open the browser console and type <div /> you'll get Uncaught SyntaxError: Unexpected token <.
So how does the browser manage to read your XML code? Depending on your configuration you have something that converts JSX to plain old JavaScript—usually it's babel.
Whenever you type <div className="foo">Hello</div> that code is translated to React.createElement('div', {className: 'foo'}, 'Hello'). As a matter of fact you could code using createElement and skip the whole JSX thing if you wanted to.
This is true for your tests too.
In your example render(<Report report={reportData} />) will be translated to render(React.createElement(Report, {report: reportData}, null)) before your test runs.
And that's why you have an error; you're trying to access the method createElement of React but you didn't import it.
Importing React will fix your test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With