How can I spy on a method to check that it was called properly?

// A spy can stub a function i.e. return a specific value and track what values it was invoked with.
// A spy only exists in the `it` or `describe` block it was defined in. 
// They are automatically removed after the `it` block has completed.
//
// When you spy on an existing function use `spyOn`

const add = (x, y) => x + y

describe('the add function', () => {
  it('should add two numbers correctly', () => {

    // Spy on the `add` function in the global namespace
    // NOTE: we use `callThrough` to ensure original behaviour of function happens
    const addSpy = spyOn(window, 'add').and.callThrough()

    // Invoke the spy
    const result = add(1, 2)

    // Check it was called correctly
    expect(addSpy.calls.any()).toBe(true)
    expect(addSpy.calls.count()).toBe(1)
    expect(addSpy).toHaveBeenCalled()

    // Check it was called with the correct arguments
    expect(addSpy).toHaveBeenCalledWith(1, 2)

    // Check it returned the correct value
    expect(result).toBe(3)

  })  
})

Last updated

Was this helpful?