【问题标题】:I am new to typescript, react and unit testing. How can I write test case for the following function with jest?我是打字稿、反应和单元测试的新手。如何用 jest 为以下函数编写测试用例?
【发布时间】:2019-04-09 19:21:09
【问题描述】:

这是一个打字稿功能。我想为此写一个测试用例。

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

【问题讨论】:

  • 嗨 Maryam,这是您函数中的所有代码吗?或者您只是想测试ageCalculate?无论哪种方式,这里似乎都缺少一些信息。如果这是您函数内部的代码,我认为它也不会像您期望的那样工作。因为你有一个 if/else 语句都返回一些东西,所以你永远不会到达它计算 ageCalculate 的区域。
  • 您好,它们是两个独立的函数。在第一个函数中,我正在计算生日剩下的天数。在第二个函数中,我正在计算年龄。我想为这两个函数编写测试。

标签: typescript jestjs testcase


【解决方案1】:

这就是我喜欢在课堂上测试我的函数的方式。我在项目的根目录下创建了一个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");
    });

});

【讨论】:

    【解决方案2】:

    我自己确实能够做到。解决方法如下:

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

    【讨论】:

      猜你喜欢
      • 2020-03-02
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2019-04-13
      • 1970-01-01
      • 2021-12-03
      • 2020-08-27
      相关资源
      最近更新 更多