gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:25:50 25 4
gpt4 key购买 nike

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

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();

最佳答案

您可以使用 .toMatch(regexpOrString)和正则表达式来做到这一点。正则表达式模式等价于 startsWith/^field?/
例如。
index.ts :

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

export { MyClass };
index.test.ts :

import { MyClass } from './';

describe('61290819', () => {
it('should pass', () => {
const myClass = new MyClass();
const property = 'field';
const message: string = myClass.generateMessage(property);
expect(message).toMatch(new RegExp(`^${property}?`));
});

it('should pass too', () => {
const myClass = new MyClass();
const property = 'f_ield'; // make some changes
const message: string = myClass.generateMessage(property);
expect(message).not.toMatch(new RegExp('^field?'));
});
});

单元测试结果:

 PASS  stackoverflow/61290819/index.test.ts (9.814s)
61290819
✓ should pass (5ms)
✓ should not pass

Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.417s

关于typescript - 如何期望字符串以指定的变量开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61290819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com