As mentioned above, the most simple comparisons can be with .toBe(expectedValue)
.
You can also use toEqual
and toStrictEqual
- for strings they all work in the exact same way.
For example:
test('string equality', () => {
const greeting = 'Hello, World!';
expect(greeting).toBe(
'Hello, World!'
);
expect(greeting).toEqual(
'Hello, World!'
);
expect(greeting).toStrictEqual(
'Hello, World!'
);
});
You can use .toContain()
to do a partial match on a string.
test('string content matching', () => {
const message =
'Welcome to our application';
expect(message).toContain('Welcome');
expect(message).toContain(
'application'
);
});
Sometimes you will want to do a regex check in a test, which can be done with .toMatch()
in either Jest or Vitest.
test('matching with RegExp', () => {
const message =
'Welcome to our application';
expect(message).toMatch(/^Welcome/);
expect(message).toMatch(
/application$/
);
expect(message).toMatch(
/Welcome.*application/
);
expect(message).toMatch(
/^Welcome to our application$/
);
});
The easiest way to check string length is exactly a size, is to use the .toHaveLength()
matcher.
If you need to do comparisons (e.g. greater than 5 chars) then I find the best way is to just get the .length
value and use .toBeGreaterThan()
.
test('string length assertions', () => {
const username = 'bobby01234';
expect(username.length).toBe(10);
expect(
username.length
).toBeGreaterThan(5);
expect(username).toHaveLength(10);
});
Note: You can also use .toHaveLength()
on arrays (see upcoming lesson). It just checks the value in expect(...)
has .length
value matching the size you pass in.
If you need to check a value matches an expected value, but you don't care about case sensitivity, then you can just turn it into .toLowerCase()
before doing your comparison.
test('string case insensitive checks', () => {
const username = 'bobBY01234';
expect(username.toLowerCase()).toBe(
'bobby01234'
);
expect(username.toUpperCase()).toBe(
'BOBBY01234'
);
});
You can also do case insensitive by doing a RegExp with the /i
modifier:
expect(username).toMatch(/bobby01234/i);
Empty strings could be checked in a couple of ways
test('advanced string validation', () => {
const emptyString = '';
const whitespaceString = ' ';
expect(emptyString).toBe('');
expect(emptyString).toHaveLength(0);
expect(emptyString).toBeFalsy();
expect(whitespaceString.trim()).toBe(
''
);
expect(whitespaceString).toHaveLength(
3
);
});
Lesson Task
In the first test, instead of using toBe()
, use a partial string match (case-insensitive).
Hint: use toContain()
or toMatch(/.../i)
for a partial, case-insensitive match.
For the second one, remember that you can use .toHaveLength(...)
.