Skip to main content

How to describe expectations in a test?

Expectations in a test are described using the construct:

javascript
expect(actualResult).matcher(expectedValue);

It compares what the function returned with what was supposed to happen.


The simplest example

js
expect(sum(2, 3)).toBe(5);

Here:

  • expect(sum(2, 3)) - the actual result
  • .toBe(5) - the expectation (matcher) that the result should equal 5

The most common matchers

MatcherWhat it checks
toBe(value)strict equality (like ===)
toEqual(obj)compares objects and arrays by content
toBeTruthy()the value is truthy
toBeFalsy()the value is falsy
toBeNull()strictly null
toBeUndefined()strictly undefined
toContain(item)the item is present in an array or string
toBeGreaterThan(num)greater than…
toBeLessThan(num)less than…

Example with different expectations

js
expect([1, 2, 3]).toContain(2); expect({ name: "Tom" }).toEqual({ name: "Tom" }); expect(10).toBeGreaterThan(5); expect(false).toBeFalsy();

The meaning of expectations

Every expectation is a statement that must be true. If even one of them does not match reality, the test fails and shows exactly what went wrong.


In other words, expectations describe how the code is supposed to behave, while Jest automatically checks whether the actual behavior matches the expected one.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.