如何在 jest 中测试 if 条件和 return 语句?

And*_*eks 1 javascript typescript jestjs ts-jest

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

const extractInfo = (description: string) => {
        const info= description.match('descriptionInformation');
        if (info) {
          return info[0];
          }
         return 'hello jest';
        };
Run Code Online (Sandbox Code Playgroud)

尝试下面的测试用例来检查 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';
        };
Run Code Online (Sandbox Code Playgroud)

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

Lia*_*iam 5

让我们将其归结为:

我想测试一下这个功能:

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

因此,要测试此功能,您需要提供一些输入并期望输出。所以你可以编写这样的测试:

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

      //test
      const result = extractInfo(Info);
    
      //expect
      expect(result).toEqual('hello jest');
   });
});
Run Code Online (Sandbox Code Playgroud)

因此,构建您的输入,运行您的测试,断言/期望它是正确的。这是适用于所有语言/框架的所有单元测试的基本单元测试模式。

这一切都说明了您的输入和输出以及您的测试仍然全部被破坏,但希望这能回答您的基本问题