Lef*_*fka 2 javascript jasmine angularjs
我正在为比较日期的函数编写 Jasmine 单元测试。我想提供一个用于今天日期的假日期。因此,我正在监视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');
})
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能只模拟今天的日期,并允许new Date(yyyy, mm, dd)创建正确的日期对象?我希望小提琴中的两个测试都能通过,即anotherDay设置为1/1/2016和today设置为12/1/2015。
业力茉莉花 v 0.1.6。
beforeEach(() => {
const fixedDate = new Date(2020, 0, 1);
jasmine.clock().install();
jasmine.clock().mockDate(fixedDate);
});
afterEach(() => {
jasmine.clock().uninstall();
});
Run Code Online (Sandbox Code Playgroud)
源代码: https: //stackoverflow.com/a/48574541