我有一个'dateRange'函数,它有不同格式的开始日期和结束日期。
dateRangeSelected = (event, value) => {
if (event && event.length == 2 && value === 'rangeSelected')
{
let statDateTime = new Date(event[0]);
let selectedTime = moment().format('hh:mm');
let startDate = moment(moment(statDateTime).format('YYYY-MM-DD') + " " + selectedTime);
this.setState({startDate : startDate });
}
}
我是在开玩笑地写测试用例。我写了这些行来达到这个函数
const components = new myComponent({ ...props });
components.dateRangeSelected(event, value);
我可以达到的功能,但这些时刻线显示为未覆盖的覆盖文件。任何想法如何做到这一点.提前感谢。
我将提取逻辑到单独的函数中。
dateRangeSelected = (event, value) => {
if (event && event.length == 2 && value === 'rangeSelected') {
const startDate = getStartDate(event[0]);
this.setState({startDate});
}
}
const getStartDate = (event) => {
const date = moment(event);
const currentDate = moment();
date.set({
hour: currentDate .hour(),
minute: currentDate.minute()
});
return date;
}
测试示例
const {
core: {
beforeEach,
describe,
it,
expect,
run
},
} = window.jestLite;
const getStartDate = (event) => {
const date = moment(event);
const currentDate = moment();
date.set({
hour: currentDate.hour(),
minute: currentDate.minute()
});
return date;
}
describe("moment", () => {
const currentDate = new Date();
beforeEach(() => {
moment.now = () => currentDate;
});
it("returns hours and minutes", () => {
const date = moment('2100-06-11 10:10:00')
expect(date.hour()).toBe(10);
expect(date.minute()).toBe(10);
})
it("returns date with current time", () => {
expect(moment(currentDate).toDate().toString()).toBe(currentDate.toString());
})
it("returns date with changed time", () => {
const date = moment(currentDate);
date.set({
hour: 10,
minute: 10
});
expect(moment(date).format("hh:mm")).toBe("10:10");
})
})
describe("getStartDate", () => {
const currentDate = new Date();
beforeEach(() => {
moment.now = () => currentDate;
});
it("returns date with current time", () => {
const startDate = getStartDate(currentDate);
const format = "YYYY-MM-DD hh:mm";
const expectedDateFormatted = moment().format(format);
expect(startDate.format(format)).toBe(expectedDateFormatted);
});
});
run().then(result => {
console.log(result);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/core.js"></script>