Uddhav Bhosle
Uddhav Bhosle

Reputation: 43

Jest: Expect function which was returned from another mocked function

My code is like this:

async function A() {
    const myObj = await b();
    myObj.create();
}

In my jest file, I mock the function b() like this:

b.mockImplementation(() => {
    return {
        create: () => '',
    }
}

Now I want to check if myObj.create() was called or not. How do I do that? Something like:

await A();
expect(b).toHaveBeenCalled();

Upvotes: 0

Views: 64

Answers (1)

hoangdv
hoangdv

Reputation: 16147

Instead of return a anonymous object, you have to return a mock object. With the mocked object, you can control the function create has to call or not.

// Mocked object with `create` property is a mock function
const mockedMyObj = {
  create: jest.fn(),
};

// b is a async function, we just mock the return value. 
b.mockResolvedValue(Promise.resolve(mockedMyObj));

// expect
await A();
expect(b).toHaveBeenCalled();
// now you can verify the `create` function
expect(mockedMyObj.create).toHaveBeenCalled();

Upvotes: 1

Related Questions