如何期望字符串以指定变量开头

问题描述 投票:0回答:1

我有一个简单的功能,可以从复杂的对象构造字符串。为了简单起见,我将为此]

public generateMessage(property: string): string {
    return `${property} more text.`;
}

我目前的测试是

    it('starts the message with the property name', () => {
        const property = 'field';
        const message: string = myClass.generateMessage(property);

        expect(message).toEqual(`${property} more text.`);
    });

这里唯一相关的是生成的消息以属性开头。有没有一种方法可以检查字符串是否以该属性开头?伪代码:

expect(message).toStartWith(property);

或者我是否必须使用startsWith()方法自行处理字符串?目前我想到的最好的解决方案是

expect(message.startsWith(property)).toBeTruthy();

我有一个简单的功能,可以从复杂的对象构造字符串。为了简单起见,我将使用这个公共的generateMessage(property:string):string {return`$ {property} more ...

typescript jestjs
1个回答
1
投票

您可以使用.toMatch(regexpOrString)和正则表达式来执行此操作。与startsWith等效的正则表达式模式为/^field?/

© www.soinside.com 2019 - 2024. All rights reserved.