Learn the basics of how to test with Jest or Vitest. This course covers the main features for writing assertions, tests, mocks, async testing, and more
Learn the basics of how to test with Jest or Vitest. This course covers the main features for writing assertions, tests, mocks, async testing, and more
You can use .toContain() to do a partial match on a string.
code
test('string content matching',()=>{const message ='Welcome to our application';expect(message).toContain('Welcome');expect(message).toContain('application');});
Regex matches
Sometimes you will want to do a regex check in a test, which can be done with .toMatch() in either Jest or Vitest.
code
test('matching with RegExp',()=>{const message ='Welcome to our application';// Starts and ends withexpect(message).toMatch(/^Welcome/);expect(message).toMatch(/application$/);// Full regex matchingexpect(message).toMatch(/Welcome.*application/);expect(message).toMatch(/^Welcome to our application$/);});
String length
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().
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.
Case insensitive checks
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.
code
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:
code
expect(username).toMatch(/bobby01234/i);
Checking for empty strings
Empty strings could be checked in a couple of ways