klefevre
klefevre

Reputation: 8735

How to simulate calls of a callback passed as parameter?

I'd like to know how to simulate calls of a callback passed as a parameter:

type YesOrNoHandler = (yesOrNo: boolean) => void
type CheckValue = (val: string, handler: YesOrNoHandler)

In this example I'd like to simulate calls of the parameter handler: YesOrNoHandler, which represents a callback.

const check = jest.fn().mockImplementation((_, handler) => {
   handler(true) // how to call `handler` outside of this scope ?
})

Actually I'm not even sure that I have to use jest for that. Does anybody have an idea on how to achieve that?

Upvotes: 0

Views: 115

Answers (1)

Lin Du
Lin Du

Reputation: 102207

Just assign the handler to a variable defined outside.

E.g.

describe('61504714', () => {
  it('should pass', () => {
    let handlerRef;
    const check = jest.fn().mockImplementation((_, handler) => {
      console.log('call check');
      handlerRef = handler;
    });
    const callback = jest.fn((yesOrNo: boolean) => (yesOrNo ? 'yes' : 'no'));
    check('_', callback);
    expect(callback).not.toBeCalled();
    const rval = handlerRef(true);
    expect(rval).toBe('yes');
    expect(check).toBeCalledWith('_', callback);
    expect(callback).toBeCalledWith(true);
  });
});

test results:

 PASS  stackoverflow/61504714/index.test.ts (11.463s)
  61504714
    ✓ should pass (33ms)

  console.log stackoverflow/61504714/index.test.ts:5
    call check

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.581s

Upvotes: 1

Related Questions