HomeAbout

Assertion

Assertions

toBe vs toEqual vs toStrictEqual

toBe is a primitive comparison.

  • use for string.

toEqual is a deep comparison.

  • use for array and objects.

Two identical objects can have identical toEqual but different toStrictEqual or toBe

  • toStrictEqual tests reference
  • toBe tests Object.is()
  • toEqual tests values

Rule: avoid toBe and prefer toStrictEqual

const a = { id: "1" }; expect(a).toEqual({ id: "1" }); // Pass expect(a).toStrictEqual({ id: "1" }); // Fail // `b` points to memory location of `a` const b = a; expect(a).toEqual(b); // Pass expect(a).toStrictEqual(b); // Pass

Special Assertions

// assertion to be implemented later it.todo() // run specified assertion exclusively describe.only() it.only() // positional injector parameter // %p is inserted to each assertion description describe.each([1, 2, 3])("each element %p exists", (el) => { test(`returns ${el}`, () => { expect(el).toBe(true); }) })

toHaveBeenCalledWith

expect(someObject).toHaveBeenCalledWith( expect.objectContaining({ "action": "PublicationPage", "category": "PublicationPage", "label": "7", "name": "n/a" }) )

Object field comparison

Matches a subset of the properties of an object:

// toMatchObject expect(someObject).toMatchObject({ active: true, data: expect.any(Array), ID: expect.any(String) }); // works with nested fields expect.objectContaining({ field: "specific value", id: expect.anything(), data: expect.objectContaining({ nestedField: expect.any(Array), }), ID: expect.any(String) }) // field-level comparison expect(someObj.fieldOne).toEqual(true) expect(someObj.fieldTwo).toEqual(expect.any(Array)) expect(someObj.fieldThree).toEqual(expect.any(String))
AboutContact