使用jest测试时出错,在moment.js行中将循环结构转换为JSON时出错

kupeojn6  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(97)

我用的是棱角分明和诙谐。我的错误发生在我在代码中添加moment.js时。
在我的组件中导入

import * as moment from "moment";

错误行

const date = moment(new Date(2023, 1, 1)).format("YYYY-MM-DD");

在spec测试中,我只调用此行所在的method

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

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();
    });
}
km0tfn4u

km0tfn4u1#

我发现了它的决定。
测试中:

component.getDate = jest.fn().mockResolvedValue(null);

你可以对任何函数做同样的事情

相关问题