英文:
Why will Jest run code that has an incorrect import statement?
问题
这个问题是我在一个JavaScript程序中遇到的,导入语句没有包括.js
扩展名。
可以理解的是,这导致程序在Node.js中失败,因为./import
不存在(而./import.js
存在)。错误信息反映了这一点:Error [ERR_MODULE_NOT_FOUND]: Cannot find module .../export
,被从...导入。
然而,使用jest
进行测试时,它似乎工作'正确'(就好像文件扩展名已经包括在内)。有人知道为什么这段代码在jest中表现正常,即使它试图导入的文件实际上并不存在吗?
我已经建立了一个非常小的存储库链接在这里,以复制这个问题(使用相同的配置)。希望这提供了关于我的问题的全部背景信息。
英文:
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.
答案1
得分: 2
当您在Jest中运行代码时,您正在使用Jest的导入系统。这比默认的JavaScript导入系统更高级。它可以做一些像“猜测”扩展名的事情。
因此,通过Jest运行的代码很可能是正确的。
查看jest.config.js
,它是否列出要尝试的扩展名?例如.js
,.jsx
,.ts
?如果是这样,那就是您的答案。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论