Unit Testing Basics — Series 3

Preview — 3 of 10 questions

What does it.each contribute?

javascript
it.each([
  ['Bombay Cat', 'bombay-cat'],
  ['  Spaced  ', 'spaced'],
  ['Ünïcode', 'unicode'],
])('slugifies %s to %s', (input, expected) => {
  expect(slugify(input)).toBe(expected);
});
AIt runs the same test repeatedly to detect flakiness
BIt merges the cases into one test, so a single failure reports them all together
CIt generates one independent test per row — each reported separately, so a failure names the exact input — while keeping the cases readable as a table that is easy to extend
DIt runs the cases in parallel, reducing the suite's duration

How does this differ from toEqual?

javascript
expect(response.body).toMatchObject({ id: expect.any(String), name: 'Bombay' });
AIt asserts the received object contains the expected properties, ignoring any others — so a response gaining a new field does not break the test, while the properties the test cares about are still checked exactly
BIt compares only the top level, never nested objects
CIt is an alias for toEqual with a clearer name
DIt ignores property values and checks only that the keys exist

What does expect.assertions(1) protect against?

javascript
it('rejects an invalid slug', async () => {
  expect.assertions(1);
  try {
    await service.findBySlug('nope');
  } catch (err) {
    expect(err).toBeInstanceOf(NotFoundException);
  }
});
AThe catch block running more than once
BThe wrong exception type being thrown
CAssertions being executed in the wrong order
DThe call not throwing at all: without it, the catch block is simply skipped, no assertion runs and the test passes green — the declaration makes "exactly one assertion must have executed" part of the contract

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.