Yet another cause of Cannot use import statement outside a module

I’m adding tests to one of our older internal CDK projects (see this post from 2022 for background on CDK and tests). When I say old, I mean that it started out on CDK 1.8.0, and the first commit is dated September 16, 2019. I’m writing some basic tests prior to upgrading it to CDK 2.118.0, and encountered a vaguely familiar error the first time I ran npm test:

1
SyntaxError: Cannot use import statement outside a module

This is a problem with the Babel Javascript compiler, and unfortunately there’s no one mistake that causes it, which makes searching for an answer difficult. Adam Nathaniel Davis wrote a great blog post on dev.to a few years ago, summing up numerous different causes and then proceeding to detail the one that he’d encountered.

I’m here for one more. The default configuration for jest was added to CDK 1.9.0; which was released on September 20, 2019. Our project didn’t have one. The file, jest.config.js, hasn’t changed in any meaningful way since then:

1
2
3
4
5
6
7
8
module.exports = {
testEnvironment: 'node',
roots: ['<rootDir>/test'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest'
}
};

Create that in the root of your project, re-run the tests, and you’re off to the races. We’ve had other issues over the years with older CDK projects, especially on the v1 to v2 jump. This mostly involved adjusting the content of package.json. A missing file is easier to overlook, especially when it’s one (like tsconfig.json or cdk.json) that you don’t pay much attention to on a day-to-day basis. This one isn’t relevant until you try to write tests for the first time.