【问题标题】:how to expect string to start with specified variable如何期望字符串以指定的变量开头
【发布时间】:2020-08-01 02:06:25
【问题描述】:

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

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

【问题讨论】:

    标签: typescript jestjs


    【解决方案1】:

    您可以使用.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 2014-03-29
      • 2014-08-05
      相关资源
      最近更新 更多