我是打字稿、反应和单元测试的新手。如何用 jest 为以下函数编写测试用例?
I am new to typescript, react and unit testing. How can I write test case for the following function with jest?
这是一个打字稿函数。我想为此写一个测试用例。
FUNCTION # 1:- TO CALCULATE DAYS LEFT IN NEXT BIRTHDAY
let daysLeft=('Birthday on ' + moment(date).format("D MMM") + ' (in ' + moment(moment(date)).add(moment(moment().format("YYYY-MM-DD")).diff(moment(date), "years") + 1, "years").diff(moment().format("YYYY-MM-DD"), "days") + ' days)');
if (birthday === today){
return ('Today is a big day!')
}
else {return daysLeft;}
}
FUNCTION # 2:- TO CALCULATE THE AGE
const ageCalculate = (date: any) : any => {
return ( moment(moment().format("YYYY-MM-DD")).diff(moment(date), "years"));
}
这就是我喜欢在 class 中测试我的功能的方式。我在项目的根目录下创建了一个 test
文件夹,并创建了某种 classYouAreTesting.spec.ts
文件。
在那个文件中,我会有以下代码
//import whatever you need
describe("Birthday class tests", () => {
it("Today is my birthday", () => {
//birthday class initializes to some arbitrary date, let's say "01-01-1994"
const birthday = new Birthday();
//getBirthday will return a string representation of the date
const result = birthday.getBirthday();
expect(result).toEqual("01-01-1994");
});
});
我自己确实能做到。解决方案如下:
test('Checking days left in next bday', () => {
expect(functions.daysleft('2016-04-10')).toBe(1);
});
test('Checking days left in next bday', () => {
expect(functions.ageCalculate('1990-04-10')).toBe(28);
});
这是一个打字稿函数。我想为此写一个测试用例。
FUNCTION # 1:- TO CALCULATE DAYS LEFT IN NEXT BIRTHDAY
let daysLeft=('Birthday on ' + moment(date).format("D MMM") + ' (in ' + moment(moment(date)).add(moment(moment().format("YYYY-MM-DD")).diff(moment(date), "years") + 1, "years").diff(moment().format("YYYY-MM-DD"), "days") + ' days)');
if (birthday === today){
return ('Today is a big day!')
}
else {return daysLeft;}
}
FUNCTION # 2:- TO CALCULATE THE AGE
const ageCalculate = (date: any) : any => {
return ( moment(moment().format("YYYY-MM-DD")).diff(moment(date), "years"));
}
这就是我喜欢在 class 中测试我的功能的方式。我在项目的根目录下创建了一个 test
文件夹,并创建了某种 classYouAreTesting.spec.ts
文件。
在那个文件中,我会有以下代码
//import whatever you need
describe("Birthday class tests", () => {
it("Today is my birthday", () => {
//birthday class initializes to some arbitrary date, let's say "01-01-1994"
const birthday = new Birthday();
//getBirthday will return a string representation of the date
const result = birthday.getBirthday();
expect(result).toEqual("01-01-1994");
});
});
我自己确实能做到。解决方案如下:
test('Checking days left in next bday', () => {
expect(functions.daysleft('2016-04-10')).toBe(1);
});
test('Checking days left in next bday', () => {
expect(functions.ageCalculate('1990-04-10')).toBe(28);
});