Home > front end >  How to mock multiple call chained function with jest
How to mock multiple call chained function with jest

Time:12-29

When i write unit test for my project, i meet the case that i need mock a function chained multiple call in mongoose module.

if it only call .populate() once like code below:

await mongoose.model("routeDetail").find({
            _id: {
                $in: requestBody.routeIds,
            },
        })
            .populate("organizationId")

i could easily mock it such as mocks/mongoose.js

module.exports = {
    model: jest.fn().mockReturnThis(),
    find: jest.fn().mockReturnThis(),
    populate: jest.fn().mockReturnThis(),
    sort: jest.fn().mockReturnThis(),
};

test/myFile.test.js

mongoose.populate = jest.fn().mockReturnValueOnce(myValue);

but... In the other case that .populate() is called multiple time such as code below, i don't know how to mock it.

await mongoose.model("routeDetail").find({
            _id: {
                $in: requestBody.routeIds,
            },
        })
            .populate("organizationId")
            .populate("deliverDetail.orderInfo")

Anyone has idea? Please help me resolve this case, many tks!

CodePudding user response:

For that specific example, you can mock the implementation:

const model = {
  find: jest.fn(() => ({
    populate: jest.fn(() => ({
      populate: jest.fn(() => Promise.resolve([])),
    })),
  })),
};

Model is an object that has a find function that returns an object with a populate function that returns an object with a populate function that returns a Promise that resolves an empty array.

CodePudding user response:

in file .test.js, write code below on case test need to mock

    mongoose.populate = jest.fn().mockReturnValue({
        populate: jest.fn().mockResolvedValueOnce({name:"mock value"})
    });

That's all. It worked for me

but in other cases, when a function contain 2 query mongoose that first query is

find().populate().populate()(call populate() twice )

and the next is

find().populate() (only call populate() once )

again, I have no idea to mock.

  • Related