Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to expect string to start with specified variable

I have a simple function constructing a string from a complex object. For the sake of simplicity I will go for this

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

My test currently is

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

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

The only thing relevant here is that the generated message starts with the property. Is there a way I can check if a string starts with that property? Pseudo code:

expect(message).toStartWith(property);

or do I have to do it on my own using the startsWith() method for strings? The best solution coming to my mind currently is

expect(message.startsWith(property)).toBeTruthy();
like image 963
Question3r Avatar asked Apr 18 '20 14:04

Question3r


1 Answers

You can use .toMatch(regexpOrString) and regexp to do this. The regexp pattern equivalent to startsWith is /^field?/

E.g.

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

unit test results:

 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
like image 78
slideshowp2 Avatar answered Nov 15 '22 08:11

slideshowp2