How to check if a set contains exact values with Jest in JS?

Article autor
September 9, 2025
How to check if a set contains exact values with Jest in JS?
Elixir Newsletter
Join Elixir newsletter

Subscribe to receive Elixir news to your inbox every two weeks.

Oops! Something went wrong while submitting the form.
Elixir Newsletter
Expand your skills

Download free e-books, watch expert tech talks, and explore open-source projects. Everything you need to grow as a developer - completely free.

Table of contents

TLDR: With jest-extended package you can write: expect([...set]).toIncludeSameMembers([value1, value2]);. If you are looking to a native, but longer solution scroll down a bit.

Let's say that you want to create a tic tac toe game solver and need to test if a function that returns possible moves from a given state works properly.

const state = [
  ['X', 'O', 'X'],
  ['X', 'O', null],
  ['O', null, 'X'],
];
const possibleMoves = new Set();
possibleMoves.add([
  ['X', 'O', 'X'],
  ['X', 'O', null],
  ['O', 'O', 'X'],
]);
possibleMoves.add([
  ['X', 'O', 'X'],
  ['X', 'O', 'O'],
  ['O', null, 'X'],
]);
const foundPossibleMoves = getPossibleMoves(state, 'O');

Jest doesn't have a built-in functions for working with a set data structure, but it greatly supports comparing arrays. You can convert set to array and check for inclusion (elements ordering does not matter), but then you also need to check if sets have equal sizes:

expect([...foundPossibleMoves]).toEqual(
  expect.arrayContaining([...possibleMoves]),
);
expect(foundPossibleMoves.size).toEqual(possibleMoves.size);

Fortunately, jest-extended package contains matcher named toIncludeSameMembers that does the both:

expect([...foundPossibleMoves]).toIncludeSameMembers([...possibleMoves]);

Jest performs deep elements comparison, so the check above should pass.

Related posts

Dive deeper into this topic with these related posts

No items found.

You might also like

Discover more content from this category

How to install local npm package in a project

In some cases, like for testing purposes, you might want to use an npm package stored on a local machine. Here is how you can do that with one simple command.

How to set default value in JavaScript’s Destructuring

Did you know that it's possible to set default value in Javascript object destructuring?

How to safely handle related database operations with Ecto Multi

Sometimes you need to do some database operations at once. A simple example: User-A transfers money to User-B. Updating just one balance at the time creates a risk of data desynchronization. What if the first DB operation goes well but updating the second user’s data fails? Sounds like a hard to catch vulnerability.