我正在使用 Angular 和 Jest。当我在代码中添加 moment.js 时发生错误。
我在组件中的导入
import * as moment from "moment";
错误线
const date = moment(new Date(2023, 1, 1)).format("YYYY-MM-DD");
在规范测试中我只是调用该行所在的方法
component.getAll();
完全错误
● Test suite failed to run
TypeError: Converting circular structure to JSON
--> starting at object with constructor '_Zone'
| property '_zoneDelegate' -> object with constructor '_ZoneDelegate'
--- property 'zone' closes the circle
at stringify (<anonymous>)
at messageParent (../../node_modules/jest-runner/node_modules/jest-worker/build/workers/messageParent.js:29:19)
调用 moment 的 getDate() 函数
getDate() {
this.selectedYear = new Date().getFullYear();
this.selectedMonth = new Date().getMonth() + 1;
this.selectedMonthData = moment(
new Date(this.selectedYear, this.selectedMonth - 1, 1)
).format("YYYY-MM-DD");
this.months = months;
this.years = [];
for (let year = 2000; year <= this.selectedYear + 1; year++) {
this.years.push({
value: year,
title: year.toString(),
});
}
}
getAll()函数调用getDate函数
getAll(): void {
...
this.getDate();
...
}
嗯...我也收到警告
Calling "moment" will crash at run-time because it's an import namespace object, not a function [call-import-namespace]
也许这是我崩溃的原因?
获取全部
getAll(): void {
Promise.all([
this.settingsService.getItem(
"group",
false
),
this.settingsService.getItem(
"serialNumber",
false
),
this.settingsService.getItem("shifts"),
this.settingsService.getItem("version")
]).then(
(res) => {
this.settings = {
group: res[0] as boolean,
serialNumber: res[1] as boolean,
shifts: (res[2] as number[]) || [],
version: res[3] as number,
};
this.getDate();
});
}
我找到了它的决定。
测试中:
component.getDate = jest.fn().mockResolvedValue(null);
您可以对任何函数执行相同的操作