Skip to content
the poor coder

jest expect string to contain substring

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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:

Text

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'.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC