glend
glend

Reputation: 1622

unable to run tests using react-testing-library "Cannot use import statement outside a module" error

here is a Sandbox. the issue can be triggered by typing npm run test -- -t "Store" into the console. The error that will be returned is Cannot use import statement outside a module because when compiled import React from "react"; is being added to util\store.test.tsx for reasons I don't understand.

The error is only encountered when using imports (and jsx) from react-testing-library

I have tried every suggestion listed here and nothing works.

my jest.config.ts is;

export default {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8"
}

and babel.config.js is;

module.exports = {
    presets: [
      'next/babel',
      ['@babel/preset-env', {targets: {node: 'current'}}],
      '@babel/preset-typescript'
    ]
  }; 

I believe this is a somewhat unique error given interactions of specific libaries used in my project which is why other suggestions have not be able to resolve the issue.

Upvotes: 1

Views: 6052

Answers (2)

glend
glend

Reputation: 1622

for reasons unknown there seemed to be a problem with my babel.config.js file (not provided in the original questions, sorry)

module.exports = {
    presets: [
      'next/babel',
      ['@babel/preset-env', {targets: {node: 'current'}}],
      '@babel/preset-typescript'
    ]
  };  

This was originally put in place to make Typescript work in Next.js but wasn't needed and was breaking Jest. Deleting the file worked, however, i have since set it to;

module.exports = {
    "presets": [
        "next/babel"
    ],
    "plugins": []
}

It was a problem with preset-env as deleting that line specifically fixed the error.

Upvotes: 0

Lin Du
Lin Du

Reputation: 102277

  1. Change JSX mode to "jsx": "react" for tsconfig.json.

  2. Add ts-jest package

  3. Modify the jest.config.ts like this:

export default {
  preset: "ts-jest/presets/js-with-ts",
  testEnvironment: "jsdom",
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8"
}
  1. npm run test -- -t "Store"

Test result:

sandbox@sse-sandbox-91opf:/sandbox$ npm run test -- -t "Store"

> [email protected] test /sandbox
> jest "-t" "Store"

 FAIL  util/store.test.tsx (32.906 s)
  ● Store: › Should work

    TestingLibraryElementError: Unable to find an accessible element with the role "h1"

    Here are the accessible roles:

      heading:

      Name "":
      <h1 />

      --------------------------------------------------

    Ignored nodes: comments, <script />, <style />
    <body>
      <div>
        <h1 />
      </div>
    </body>

       6 |   it("Should work", () => {
       7 |     render(<h1></h1>);
    >  8 |     expect(screen.getAllByRole("h1")).toBeInTheDocument();
         |                   ^
       9 |   });
      10 |   it("definitely work", () => {
      11 |     expect(true).toBe(true);

      at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:38:19)
      at node_modules/@testing-library/dom/dist/query-helpers.js:90:38
      at node_modules/@testing-library/dom/dist/query-helpers.js:130:15
      at Object.<anonymous> (util/store.test.tsx:8:19)

----------|---------|----------|---------|---------|------------------------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|------------------------------------
All files |   36.17 |      100 |       0 |   36.17 |
 maths.ts |   11.11 |      100 |       0 |   11.11 | 1-5,7-9
 notes.ts |   37.87 |      100 |       0 |   37.87 | ...46,63-94,98-111,113-116,118-132
----------|---------|----------|---------|---------|------------------------------------
Test Suites: 1 failed, 2 skipped, 1 of 3 total
Tests:       1 failed, 30 skipped, 1 passed, 32 total
Snapshots:   0 total
Time:        37.472 s, estimated 49 s
Ran all test suites with tests matching "Store".
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test: `jest "-t" "Store"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/sandbox/.npm/_logs/2021-11-25T04_42_32_701Z-debug.log

Test environment setup correctly, but your test case failed.

CodeSandbox

Upvotes: 1

Related Questions