【问题标题】:Jest importing MomentJS to unejected React app开玩笑将 MomentJS 导入到未弹出的 React 应用程序
【发布时间】:2018-02-12 09:06:59
【问题描述】:

我有一个带有 MomentJS (2.20.1) + MomentJS (0.5.14) 时区的 ReactJS 应用程序。

我想为此 .js 文件创建单元测试:

// dateHelper.js
import * as moment from "moment";
export function someFunc() {
   // some operations with moment.utc() and moment()
}

这是我的测试文件:

// dateHelper.test.js
const dateHelper = require("../dateHelper");

test("format date properly", () => {
    // ...
});

但我收到 TypeError: moment is not a function 错误。

如何在 dateHelper.js 中导入 momentJS 以使其与 Jest 正常工作?

【问题讨论】:

  • 调用模块命名空间对象,例如import * as ns from 'm';创建的,是非法的JavaScript。它抛出。使用const moment = require('moment');import moment from 'moment';。此外,避免import/export 语法与require/exports 混合使用。
  • @AluanHaddad 所以你建议我像这样“导入”时刻:const moment = require("moment"); in dateHelper。这次我收到TypeError: moment(...).tz is not a function 错误。是 webpack 自动导入的 Moment 的时区插件。
  • 我看不到它在哪里说它会自动导入。无论如何,您不能import * as ns from 'm'; ns();。必须扔。

标签: javascript reactjs unit-testing momentjs jestjs


【解决方案1】:

尝试:

import moment from 'moment'

假设你正在使用 moment 节点模块

【讨论】:

  • 得到“TypeError: (0, _moment2.default)(...).tz is not a function”错误。 tz() 函数带有 Moment 时区 (momentjs.com/timezone),由核心 'moment' 包的 webpack 配置自动检测和导入。
  • import moment from "moment-timezone 看起来工作正常。我会做一些测试以确保导入 moment-timezone 而不是 moment 不会破坏任何东西。
猜你喜欢
  • 2017-05-20
  • 2021-11-30
  • 1970-01-01
  • 2021-09-25
  • 2017-08-25
  • 2019-02-14
  • 2020-04-12
  • 2020-05-29
  • 2020-06-21
相关资源
最近更新 更多