Website-Suche

typescript - Wie erwartet man, dass ein String mit einer bestimmten Variable beginnt


Ich habe eine einfache Funktion, die einen String aus einem komplexen Objekt erstellt. Der Einfachheit halber werde ich mich dafür entscheiden.

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

Mein Test ist derzeit

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

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

Das Einzige, was hier relevant ist, ist, dass die erzeugte Nachricht mit der Eigenschaft beginnt. Gibt es eine Möglichkeit, zu überprüfen, ob ein String mit dieser Eigenschaft beginnt? Pseudocode:

expect(message).toStartWith(property);

oder muss ich es selbst mit der startsWith()-Methode für Zeichenketten machen? Die beste Lösung, die mir derzeit in den Sinn kommt, ist

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

Antwort #1

Sie können .toMatch(regexpOrString) und regexp verwenden, um dies zu tun. Das regexp-Muster, das startsWith entspricht, ist /^field?/

z. B.

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

Einheitstest-Ergebnisse:

 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

Antwort #2

Die Antwort von @slideshowp2 ist korrekt, aber das ? ist nicht nötig, da es nur null oder einmal bedeutet.

also ist das Folgende ausreichend

expect("this is a test").toMatch(/^this/);

Verwandte Artikel