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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With