jest test array code example
Example 1: jest test array of objects
const users = [{id: 1, name: 'Hugo'}, {id: 2, name: 'Francesco'}];
test('we should have ids 1 and 2', () => {
expect(users).toEqual(
expect.arrayContaining([
expect.objectContaining({id: 1}),
expect.objectContaining({id: 2})
])
);
});
Example 2: jest check array of string
const fruits = ['apple', 'cat'];
test('should have array of string', () => {
expect(fruits).toEqual(
expect.arrayContaining([expect.any(String)])
);
});
Example 3: Jest toContain
# 1. Use '.toContain' when you want to check that an item is in an array.
# 2 '.toContain' can also check whether a string is a substring of another string.
test('the flavor list contains lime', () => {
expect(['lime', 'mangle']).toContain('lime');
});
test('the flavor list contains lime', () => {
expect("lime juice").toContain('lime');
});