Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何期望字符串以指定变量开头_Typescript_Jestjs - Fatal编程技术网

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

Typescript 如何期望字符串以指定变量开头,typescript,jestjs,Typescript,Jestjs,我有一个从复杂对象构造字符串的简单函数。为了简单起见,我会这样做 public generateMessage(property: string): string { return `${property} more text.`; } 我目前的测试是 it('starts the message with the property name', () => { const property = 'field'; const message

我有一个从复杂对象构造字符串的简单函数。为了简单起见,我会这样做

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.startsWith(property)).toBeTruthy();
这里唯一相关的是生成的消息以属性开头。有没有办法检查字符串是否以该属性开头?伪代码:

expect(消息).toStartWith(属性)

或者我必须自己使用字符串的
startsWith()
方法来完成吗?我现在想到的最好的解决办法是

    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.startsWith(property)).toBeTruthy();
可以使用和regexp执行此操作。等效于的regexp模式是
/^field?/

例如

index.ts

class-MyClass{
公共生成消息(属性:string):string{
返回`${property}更多文本。`;
}
}
导出{MyClass};
index.test.ts

从“/”导入{MyClass};
描述('61290819',()=>{
它('应该通过',()=>{
const myClass=new myClass();
常量属性='字段';
const message:string=myClass.generateMessage(属性);
expect(message).toMatch(新的RegExp(`^${property}?`));
});
它('也应该通过',()=>{
const myClass=new myClass();
const属性='f_ield';//进行一些更改
const message:string=myClass.generateMessage(属性);
expect(message).not.toMatch(新RegExp(“^field”);
});
});
单元测试结果:

PASS stackoverflow/61290819/index.test.ts(9.814s)
61290819
✓ 应通过(5ms)
✓ 不应该通过
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:11.417秒