【问题标题】:Jest stranspiles code differently then ts-nodeJest 编译代码的方式与 ts-node 不同
【发布时间】:2021-01-18 00:24:25
【问题描述】:

在正常运行项目并在 Jest 中运行时,我无法让我的代码工作。

运行项目需要 dayjs 的这种导入:

import * as dayjs from 'dayjs';
import * as utc from 'dayjs/plugin/utc';
import * as customParseFormat  from 'dayjs/plugin/customParseFormat';

npm run dev (nodemon --exec ./node_modules/.bin/ts-node ./src/app.ts):没有问题

开玩笑: TypeError: t is not a function

运行 Jest 测试需要 dayjs 的这种导入:

import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import customParseFormat  from 'dayjs/plugin/customParseFormat';

npm run dev (nodemon --exec ./node_modules/.bin/ts-node ./src/app.ts):

dayjs.extend(utc);
      ^
TypeError: Cannot read property 'extend' of undefined`

开玩笑:成功了!

所以现在我不可能编写测试。为什么它的转译方式不同?

【问题讨论】:

  • 这里的问题在于模块互操作的配置方式(* 和默认导出不匹配)。

标签: import jestjs es6-modules dayjs


【解决方案1】:

就我而言,

tsconfig.json

{
  "compilerOptions": {
    "esModuleInterop": true
  }
}

解决了。

【讨论】:

    【解决方案2】:

    我切换到ts-jest,它解决了我的问题。我假设我可以编写 JS 测试来测试 TS 代码,但我认为这是不可能的。

    【讨论】:

    • 可以编写JS测试来测试TS代码。 Jest 自己不会做任何事情。它使用转译器来转译代码。默认使用 Babel,它可以通过插件 jestjs.io/docs/en/getting-started#using-typescript 处理 TS。无论如何,ts-jest 是一个更好的工具。
    猜你喜欢
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多