“import https is undefined when using Jest with ts-jest (TypeScript)”

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

import https is undefined when using Jest with ts-jest (TypeScript)

问题

Issue: 在导入 Node.js 的本地模块 https 时出现 undefined

dummy.spec.file(我的测试文件)

  1. import https from "https";
  2. it("总是为真", () => {
  3. console.log("https:");
  4. console.log(https); // <- 这是 undefined
  5. expect(true).toBe(true);
  6. });

jest.config.js(Jest 配置文件)

  1. /** @type {import('ts-jest').JestConfigWithTsJest} */
  2. module.exports = {
  3. preset: 'ts-jest',
  4. testEnvironment: 'node',
  5. };

Node.js 版本:v16.13.0
依赖项:

  1. "dependencies": {
  2. "jest": "^29.6.2",
  3. "ts-jest": "^29.1.1"
  4. },
  5. "devDependencies": {
  6. "@types/jest": "^29.5.3"
  7. }

如何使 https 在测试文件(jest + TypeScript)中正常工作?

英文:

Issue: importing Nodejs native module https is undefined

dummy.spec.file (my testing file)

  1. import https from &quot;https&quot;;
  2. it(&quot;always true&quot;, () =&gt; {
  3. console.log(&quot;https:&quot;);
  4. console.log(https); // &lt;- this is undefined
  5. expect(true).toBe(true);
  6. });

jest.config.js (Jest config file)

  1. /** @type {import(&#39;ts-jest&#39;).JestConfigWithTsJest} */
  2. module.exports = {
  3. preset: &#39;ts-jest&#39;,
  4. testEnvironment: &#39;node&#39;,
  5. };

Nodejs version: v16.13.0
Dependencies:

  1. &quot;dependencies&quot;: {
  2. &quot;jest&quot;: &quot;^29.6.2&quot;,
  3. &quot;ts-jest&quot;: &quot;^29.1.1&quot;
  4. },
  5. &quot;devDependencies&quot;: {
  6. &quot;@types/jest&quot;: &quot;^29.5.3&quot;
  7. }

How can I make https work properly inside a testing file (jest + typescript) ?

答案1

得分: 0

可能的原因之一可能是您的TypeScript配置。检查是否与https模块导入存在任何问题。
在您的tsconfig.json文件中,请确保您有"module": "CommonJS"和"esModuleInterop": true

  1. {
  2. "compilerOptions": {
  3. // ...
  4. "module": "CommonJS",
  5. "esModuleInterop": true,
  6. // ...
  7. }
  8. }
英文:

One possible reason could be your Typescript configuration. Check that if it's causing any issues with the https module import.
In your tsconfig.json file, make sure you have "module": "CommonJS" and "esModuleInterop": true

  1. {
  2. &quot;compilerOptions&quot;: {
  3. // ...
  4. &quot;module&quot;: &quot;CommonJS&quot;,
  5. &quot;esModuleInterop&quot;: true,
  6. // ...
  7. }
  8. }

huangapple
  • 本文由 发表于 2023年8月5日 07:00:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839512.html
匿名

发表评论

匿名网友

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

确定