我正在尝试在 React 中做一个简单的单元测试来测试组件是否呈现。不幸的是,当我输入 yarn test
时,它会返回如下内容:
> react-scripts test
FAIL src/components/OfficeProduction/GrossCommissionIncome/GCI_Table/GCI_Table.test.js
● Test suite failed to run
C:\Users\Me\source\repos\ui\node_modules\@ui-comps\core\build\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import UxAnchor from './UxAnchor';
^^^^^^^^
SyntaxError: Unexpected identifier
1 | import React, {Component} from 'react';
> 2 | import {
| ^
3 | UxButton,
4 | UxCard,
5 | UxCardBody,
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
at Object.<anonymous> (src/components/OfficeProduction/GrossCommissionIncome/GCI_Table/index.js:2:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 3.855s
Ran all test suites related to changed files.
这与 transformIgnorePatterns 有关系吗?我安装 yarn 时没有 jest.config.js。感谢您的帮助。
我已经安装了最新版本的 React-Testing-Library 和 Jest-dom。我只是简单地输入了 Yarn Test,它总是给我导入错误。我试图忽略节点模块,只对其进行单元测试以查看组件是否呈现。
这是单元测试的文件**GCI_Table.test.js*:
import React from "react";
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import GCIRetainCoachTable from "./index";
it('renders the component', () => {
const {asFragment} = render(<GCIRetainCoachTable></GCIRetainCoachTable>);
expect(asFragment()).toMatchSnapshot();
// const container = render(<GCIRetainCoachTable></GCIRetainCoachTable>)
// expect(container.firstChild).toMatchSnapshot()
})
预期结果:测试通过组件渲染
实际结果: 测试甚至没有运行。
最佳答案
由于可能使用 babel 将 import/export
转译为 require
,因此您需要安装 babel-jest
npm i -D babel-jest
或者使用 yarn
yarn add --dev babel-jest
有关 Jest Getting started 的更多信息
关于javascript - 在 react-testing-library 中运行单元测试时出现意外标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58383468/