Javascript 如何测试jest中的条件和返回语句?

Javascript 如何测试jest中的条件和返回语句?,javascript,typescript,jestjs,ts-jest,Javascript,Typescript,Jestjs,Ts Jest,我刚开始学笑话。 使用Jest测试If case和return语句的函数的其他方法有哪些? 这是用Jest测试的函数 const extractInfo = (description: string) => { const info= description.match('descriptionInformation'); if (info) { return info[0]; } return 'h

我刚开始学笑话。 使用Jest测试If case和return语句的函数的其他方法有哪些? 这是用Jest测试的函数

const extractInfo = (description: string) => {
        const info= description.match('descriptionInformation');
        if (info) {
          return info[0];
          }
         return 'hello jest';
        };
尝试下面的测试用例进行检查 Info.test.ts

  test('extractInfo method to be defined', () => {
    expect(extractInfo ).toBeDefined();
  });

  test('extractInfo to be called when Info has blank string', () => {
    const BLANK_STRING = '';
    expect(extractInfo ).toHaveBeenCalled();
    expect(extractInfo ).toHaveBeenCalledWith(BLANK_STRING);
  })

    const extractInfo = (Info: string) => {
        const info= description.match(jestinformation);
        if (info) {
          return info[0];
          }
         return 'hello jest';
        };

请提供覆盖每一行的方法。谢谢

让我们把这归结为:

我想测试这个函数:

const extractInfo = (Info: string) => {
        const info= description.match(jestinformation);
        if (info) {
          return info[0];
          }
         return 'hello jest';
        };
因此,要测试这个函数,您需要提供一些输入并期望输出。所以你可以写一个这样的测试:

describe('extractInfo', () => {
   test('test 1', () => {
      //inputs
      const Info = '';
      const description = '';
      const jestinformation = '';

      //test
      const result = extractInfo(Info);
    
      //expect
      expect(result).toEqual('hello jest');
   });
});
因此,构建您的输入,运行测试,断言期望它是正确的。这是适用于所有语言/框架中的所有单元测试的基本单元测试模式


所有这些都表明,您的输入和输出以及您的测试仍然存在问题,但希望这能回答expect(extractInfo).tohaveincall()没有任何意义,你从不调用它,它不是一个模拟。真的很不清楚你想在这里做什么。“测试”不是有效的目标。什么是
说明
,什么是
JestinInformation
?你的预期产量是多少?为什么要在函数中添加变量
Info
,然后再也不用它呢?从字面上看,这一切都没有任何意义sense@Liam,更新问题。基本上我有这个函数的javascript函数extractInfo,我需要使用Jest编写测试用例。根据我的理解,预期输出可能是字符串匹配的,也可能不是字符串匹配的。如果您可以向我解释如何使用Jest和不同的测试用例覆盖每一行,请在这里回答,谢谢。我想在更新问题之后,现在已经很清楚了。你们的编辑并没有澄清,你们只是以稍微不同的顺序说了同样的话。我建议您阅读一下什么是单元测试,因为您似乎对这里的基本原则感到困惑。要测试
extractInfo
,您需要说明如果我输入x,我希望从这个函数中得到y。你目前的“测试”(坦率地说)根本不存在是的,因此我在@Liam上发布了这个问题,以检查这有什么问题。请使用Jest编写测试用例,简单地说,您编写的输入是X,输出是Y。您可以在同一个测试用例上编写测试用例,我会检查它