Jest&React&Typescript&React-Testing-Library错误

时间:2019-10-13 16:38:31

标签: javascript reactjs typescript unit-testing jestjs

我有一个使用Typescript的React / NextJS项目设置,并且正在使用Jest和React Testing库添加单元测试。

我的组件的单元测试如下:

import React from 'react';
import '@testing-library/jest-dom/extend-expect';
import { render } from '@testing-library/react';

import AppLayout from '.';

describe('<AppLayout>', () => {
  it('renders children', () => {
    const children = 'Test';
    const props = { pathname: '/' };
    const component = <AppLayout {...props}>{children}</AppLayout>;
    const { getByText } = render(component);
    expect(getByText(children)).toBeInTheDocument();
  });
});

这将引发以下错误:

Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

我的项目中有一些关键文件可以提供帮助:

.babelrc

{
  "env": {
    "development": {
      "presets": ["next/babel"],
      "plugins": ["babel-plugin-styled-components"]
    },
    "production": {
      "presets": ["next/babel"],
      "plugins": [
        "@babel/plugin-transform-react-inline-elements",
        ["babel-plugin-styled-components", { "displayName": false }]
      ]
    }
  }
}

tsconfig.js

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "preserve",
    "isolatedModules": true,
    "lib": [
      "dom",
      "es2017"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "removeComments": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    ".next",
    "node_modules"
  ]
}

jest.config.js

module.exports = {
  roots: ['./'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
};

我的项目可以编译并正常运行,但是我想我需要解决一些配置问题才能使单元测试正确运行。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

jest.config.js与Typescript,Jest,React Testing库一起使用,而没有Babel。 要对其进行测试,请执行:

git clone https://github.com/winwiz1/crisp-react.git
cd crisp-react/client
yarn && yarn test

尽管由于默认设置testEnvironment: 'jsdom'确实不是必需的,但是您可以查看其他设置。

作为附带说明,Babel是一款wonderful软件,但您可以考虑设置"target": "es5"并改用react-app-polyfill