hatellla
hatellla

Reputation: 5132

Access jest.fn function inside another one

I have following case while writing jest unit test cases:

elasticsearch.Client = jest.fn().mockImplementation(() => {
      return {
        update: jest.fn().mockImplementation(() => {
            return {}
        })
     }
});

Now, I want to do some expect on update function call. How can I access update function here in test case.

I can access elasticsearch.Client and its mock variable as elasticsearch.Client.mock. But how can I access similarly the update function?

Upvotes: 1

Views: 292

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12071

You can try moving the mock function for update to the outer scope:

const updateMock = jest.fn().mockImplementation(() => {
  return {}
});

elasticsearch.Client = jest.fn().mockImplementation(() => {
  return {
    update: updateMock
  }
});

Then you can use updateMock in your assertions. For example:

expect(updateMock).toHaveBeenCalled()

Upvotes: 2

Related Questions