Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I just started to write unit tests (jest) for my create-react-app project witten in Typescript and I'm having issues getting started.

I keep getting errors about: SyntaxError: Cannot use import statement outside a module .

Basically I ran yarn jest --init and did this configuration:

√ Would you like to use Typescript for the configuration file? ... yes
√ Choose the test environment that will be used for testing » jsdom (browser-like)
√ Do you want Jest to add coverage reports? ... yes
√ Which provider should be used to instrument code for coverage? » babel
√ Automatically clear mock calls, instances and results before every test? ... yes
// jest.config.ts
export default {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",

When I ran yarn test this is what I got:

$ yarn test
yarn run v1.22.19
$ jest
 FAIL  tests/components/button.test.tsx
  ● Test suite failed to run
    Jest encountered an unexpected token
    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
    By default "node_modules" folder is ignored by transformers.
    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation
    Details:
    D:\my-project\tests\components\button.test.tsx:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { BUTTON_TYPE_CLASSES, getButton } from '../../src/components/button/button.component';
                                                                                      ^^^^^^
    SyntaxError: Cannot use import statement outside a module
      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
 PASS  tests/utils/delete.test.js
-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 | 
 delete.js |     100 |      100 |     100 |     100 | 
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 failed, 1 passed, 2 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        1.719 s, estimated 2 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

The tests that pass all use Common JS syntax so there were no issues with them. But the tests I wrote for the button component is like this:

import { BUTTON_TYPE_CLASSES, getButton } from '../../src/components/button/button.component';
import { BaseButton, GoogleSignInButton, InvertedButton } from '../../src/components/button/button.styles';
describe('BUTTON COMPONENT', () => {
    it('returns base button', () => {
        expect(typeof getButton()).toEqual(typeof BaseButton);

How do I start unit testing my React project written in Typescript?

First install ts-jest npm package.

And add preset: 'ts-jest' to the jest.config.ts so TypeScript test files are transformed first by ts-json.

Your new jest.config.ts:

// jest.config.ts
export default {
  preset: 'ts-jest',
  transform: { '^.+\\.ts?$': 'ts-jest' },
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
                It's frustrating that the jest --init script doesn't do this for you. The transform line is optional - you mostly just need the preset: 'ts-jest' part. You also have to install ts-jest for this to work.
– Ryan Wheale
                Oct 26, 2022 at 19:46
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.