"Jest failed to parse a file" ... "SyntaxError: Cannot use import statement outside a module"
See original GitHub issueToday i started a new project from scratch using JEST and to my surprised i encountered this error when trying to create a server using MongoMemoryServer on my beforeEach hook.
Do i have to tweak something on jest config to make it work? I have used this setup before with an older version of mongodb-memory-server and it worked like a charm… Something must have changed either on mongodb-memory-server or i haven’t noticed
jest.config
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
roots: ["<rootDir>/src"],
// the following line is needed in order to grab modules from the
// src folder without the need to write them relatively
moduleDirectories: ["node_modules", "src"],
};
typescript test file
...
describe("POST /my-end-point", () => {
beforeAll(async () => {
mongod = await MongoMemoryServer.create();
// const uri = mongod.getUri();
// await ConnectMongoose(uri);
});
...
}
error
… " 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." … … “/home/…/node_modules/mongodb-memory-server-core/node_modules/mongodb/src/bson.ts:1 ({“Object.<anonymous>”:function(module,exports,require,__dirname,__filename,jest){import type {”“”

Issue Analytics
- State:
- Created a year ago
- Comments:6
Top Related StackOverflow Question
this seems to solve the situation!
i have tried the reproduction-repo and can reproduce it, i could also single it down to the jest option
moduleDirectories, which when manually set seems like jest will search all specified paths for all possible file extension (seemingly regardless what nestedpackage.jsonfiles specify)things you could try to workaround this issue:
srcto<rootdir>/srcmodulePaths: ["<rootdir>/src"]pathsNote: i have never used such path mapping before, so i dont know if the listed workaround will work properly, i also have never used this jest option, so i also dont know how to handle that properly but i know that this does not seem to be a problem with MMS