【发布时间】: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