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

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

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

问题

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

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

import https from "https";

it("总是为真", () => {
  console.log("https:");
  console.log(https); // <- 这是 undefined
  expect(true).toBe(true);
});

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

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

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

"dependencies": {
  "jest": "^29.6.2",
  "ts-jest": "^29.1.1"
},
"devDependencies": {
  "@types/jest": "^29.5.3"
}

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

英文:

Issue: importing Nodejs native module https is undefined

dummy.spec.file (my testing file)

import https from &quot;https&quot;;

it(&quot;always true&quot;, () =&gt; {
  console.log(&quot;https:&quot;);
  console.log(https); // &lt;- this is undefined
  expect(true).toBe(true);
});

jest.config.js (Jest config file)

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

Nodejs version: v16.13.0
Dependencies:

  &quot;dependencies&quot;: {
    &quot;jest&quot;: &quot;^29.6.2&quot;,
    &quot;ts-jest&quot;: &quot;^29.1.1&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@types/jest&quot;: &quot;^29.5.3&quot;
  }

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

答案1

得分: 0

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

{
    "compilerOptions": {
        // ...
        "module": "CommonJS",
        "esModuleInterop": true,
        // ...
    }
}
英文:

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

{
    &quot;compilerOptions&quot;: {
        // ...
        &quot;module&quot;: &quot;CommonJS&quot;,
        &quot;esModuleInterop&quot;: true,
        // ...
    }
}

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:

确定