jest expect string to contain substring

Jest Expect String to Contain Substring

When working with Jest, it is common to check if a string contains a particular substring. This can be done using the expect method that Jest provides. Here are a few ways you can do this:

Method 1: Using the toContain Matcher

The easiest and most straightforward way to check if a string contains a substring is to use the toContain matcher. Here is an example:


expect('hello world').toContain('world');

This test will pass because the string 'hello world' contains the substring 'world'.

Method 2: Using a Regular Expression

If you need more control over the pattern that you are looking for in the string, you can use a regular expression instead. Here is an example:


expect('hello world').toMatch(/world/);

This test will also pass because the regular expression /world/ matches the substring 'world' in the string 'hello world'.

Method 3: Using the includes Method

If you are not using Jest or prefer to use a different method, you can still check if a string contains a substring using the includes method. Here is an example:


const str = 'hello world';
const substr = 'world';

expect(str.includes(substr)).toBe(true);

This test will pass because the string 'hello world' contains the substring 'world'.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe