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



我刚开始学习Jest。使用Jest测试If case和return语句的此函数的其他方法是什么?这是用Jest 测试的功能

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

尝试了以下测试用例进行检查信息测试

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

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

所有这些都说明了你的输入和输出以及你的测试仍然是一团糟,但希望这能回答你的基本问题

最新更新