Jest createSpyObj

Viewed 30686

With Chai, you can create a spy object as follows:

chai.spy.object([ 'push', 'pop' ]);

With jasmine, you can use:

jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']);

What's the Jest equivalent?

Context: I am currently migrating a (typescript) Jasmine tests to (typescript) Jest. The migration guide is basically useless in this case: https://facebook.github.io/jest/docs/migration-guide.html As with any relatively new tech, there's nothing that can easily be found in the docs about this.

4 Answers

Based on @Max Millington answer I found solution with jest.fn() method:

  1. Create mocked object:

const tape: any = {};

  1. Add required method(s) for mocked object

tape['play'] = jest.fn();

  1. You can spyOn mocked methods but first assign it to real object, for example I'm using component instance:

    // GIVEN
    comp.realTape = tape
    
    // WHEN
    spyOn( comp.realTape , 'play')
    comp.method()
    
    // THEN
    expect(comp.realTape.play).toHaveBeenCalledTimes(1)
    
Related