为什么 Jest 会运行具有错误导入语句的代码?

huangapple go评论64阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月9日 15:23:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定