如何测试条件并在玩笑中返回语句?

问题描述

我刚刚开始学习Jest。 还有什么其他方法可以使用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');
   });
});

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

所有人都说过您的输入和输出以及您的测试仍然被弄乱了,但希望这能回答your basic question

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...