Search code examples
typescriptjestjstestcase

I am new to typescript, react and unit testing. How can I write test case for the following function with jest?


this is a typescript function. I want to write a test case for this.

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")); 
           }

Solution

  • This is how I like to test my functions in a class. I create a test folder at the root of my project and create some sort of classYouAreTesting.spec.ts file.

    In that file, i would have the following code

    //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");
        });
    

    });