首页 > 解决方案 > 如何对momentjs进行单元测试

问题描述

如何对这种代码进行单元测试?我为此使用 JEST 在此处输入图像描述

标签: reactjsjestjs

解决方案


我只需在我的测试文件中导入函数,然后编写将日期作为参数传递给函数的测试,然后期待从这些函数返回的值。

像这样的东西:

import {
  formatDate,
  startEndDate
} from "./index.js";

describe("formatDate", () => {
  it("should format date properly", () => {
    expect(formatDate(new Date("01/12/1992"))).toBe("Jan 12, 1992");
  });
  // More such tests here with different values of dates.
});

describe("startEndDate", () => {
  it("should return start and end date in proper format", () => {
    expect(startEndDate(new Date("01/12/1992"), new Date("12/12/1992"))).toBe(
      "01/12/1992 - 12/12/1992"
    );
  });
  // More such tests here with different values of start and end dates.
});

这是您的参考的工作 CodeSandbox 示例

PS:忽略Exceeded timeout of 5000ms for a test.你在结果中看到的测试。我们编写的 onces(2 测试) 已经通过。


推荐阅读