SyntaxError: Unexpected token, expected “</>”

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 04:12:31

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/53305638/syntaxerror-unexpected-token-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!