CaribouCode
CaribouCode

Reputation: 14438

Jest & React & Typescript & React-Testing-Library error

I have a React/NextJS project setup using Typescript and am adding unit testing with Jest and React Testing Library.

A unit test for my component looks like this:

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();
  });
});

This throws the following error:

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".

Here's some key files in my project to help:

.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',
  },
};

My project compiles and runs fine but I'm guessing there's some configuration issue I need to fix to get my unit tests running correctly. Any ideas?

Upvotes: 0

Views: 2371

Answers (1)

winwiz1
winwiz1

Reputation: 3174

This jest.config.js works with Typescript, Jest, React Testing Library and without Babel. To test it works, execute:

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

Although testEnvironment: 'jsdom' is not really needed due to being the default, you can look at the other settings.

As a sidenote, Babel is a wonderful software but you might consider setting "target": "es5" and using react-app-polyfill instead.

Upvotes: 0

Related Questions