Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isolatedModules error on Jest test with Create React App and TypeScript?

I've started a Create React App project with --typescript. When I write a test Im getting a compiler error:

// something-test.tsx
test('something', ()=>{
  expect(1).toBe(1)
})

The error is:

TS1208: All files must be modules when the '--isolatedModules' flag is provided.

From googling I thought the fix was to create a jest.config.tsx with:

module.exports = {
  roots: ["<rootDir>/src"],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"]
};

However it's made no difference.

like image 343
Evanss Avatar asked Sep 09 '19 19:09

Evanss


People also ask

How do you fix isolatedModules?

The error "Cannot be compiled under '--isolatedModules' because it is considered a global script file" occurs when we have a file in our project that doesn't contain an import or export statement. To solve the error, add an export {} line to the file to make it an ES module.

What is TypeScript isolatedModules?

Setting the isolatedModules flag tells TypeScript to warn you if you write certain code that can't be correctly interpreted by a single-file transpilation process. It does not change the behavior of your code, or otherwise change the behavior of TypeScript's checking and emitting process.

Is jest included in Create react app?

Create React App uses Jest as its test runner. To prepare for this integration, we did a major revamp of Jest so if you heard bad things about it years ago, give it another try.


1 Answers

You do not have any import statements in your code. This basically means you are not testing anything outside of the test file.

If you test something that is not in the test code (and therefore import something), the test file will become a module and the error will go away 🌹

like image 130
basarat Avatar answered Sep 25 '22 18:09

basarat