Why will Jest run code that has an incorrect import statement?

This issue I am having is that I had a mistake in a javascript program; the import line did not include the .js extension.

The understandably meant that the program failed to with node as ./import does not exist (./import.js does). The error I reflected this Error [ERR_MODULE_NOT_FOUND]: Cannot find module .../export' imported from ....

However, when testing with jest, it works ‘correctly’ (as if the file extension was included). Does anyone know why this code is ‘correct’ for jest even though the file it is trying to import from does not really exist?

I have setup a very small repo here that replicates this issue (with the same configs). Hopefully this provides all full context regarding my issue.

>Solution :

When you run code in JEST, you are using JEST’s import system

This is more advanced than the default Javascript import system. It can do things like "guessing" extensions.

Therefore the code likely is running correctly via JEST.

Look in jest.config.js

Does it list which extensions to try? e.g. .js, .jsx, .ts?

If so, that is your answer.

Leave a Reply