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

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.
Work with a team that keeps learning and building better software every day.
Related posts
Dive deeper into this topic with these related posts
You might also like
Discover more content from this category
There are a bunch of operations you may want to perform before the rendered response in conn is sent to the client, such as minification. In this post I'll show you how to do it easily.
People will tell you it's an antipattern, but what if a library needs you to do this?
With pure function React Components you're not allowed to use lifecycle methods like componentDidMount or componentWillUnmount.
