gpt4 book ai didi

javascript - Jasmine 单元测试中仅模拟今天的日期

转载 作者:行者123 更新时间:2023-12-02 15:07:10 25 4
gpt4 key购买 nike

我正在为比较日期的函数编写 Jasmine 单元测试。我想提供一个用于今天日期的假日期。因此,我监 window 口对象上的 Date 方法并返回预定义的日期。

这工作正常,但在我正在测试的函数中,我还从字符串中读取日期并调用 new Date(yyyy, mm, dd) 将它们转换为日期。发生这种情况时,这些值将替换为我提供的模拟日期。

这是一个例子:

var checkDate = function () {
return { today: new Date(), anotherDay: new Date(2016, 0, 1) }
};

var createDate = function (year, month, date) {
var overrideDate = new Date(year, month, date);
spyOn(window, 'Date').andCallFake(function () {
return overrideDate;
})
}

var dates;

describe("checkDate", function() {
beforeEach(function() {
createDate(2015, 11, 1);
dates = checkDate();
})
it("today has a value of 12/1/2015", function() {
expect(dates.today.toLocaleDateString()).toBe('12/1/2015');
});
it("anotherDay has a value of 1/1/2016", function() {
expect(dates.anotherDay.toLocaleDateString()).toBe('1/1/2016');
})
});

Here's a JSFiddle example of the issue.

如何仅模拟今天的日期,并允许 new Date(yyyy, mm, dd) 创建正确的日期对象?我希望 fiddle 中的两个测试都通过,即 anotherDay 设置为 1/1/2016today 设置为 2015 年 12 月 1 日

业力 Jasmine v 0.1.6。

最佳答案

最好使用Jasmine Clock API

beforeEach(() => {
const fixedDate = new Date(2020, 0, 1);
jasmine.clock().install();
jasmine.clock().mockDate(fixedDate);
});

afterEach(() => {
jasmine.clock().uninstall();
});

源代码:https://stackoverflow.com/a/48574541

关于javascript - Jasmine 单元测试中仅模拟今天的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35043950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com