How test a function inside of callback with jest


My applications is a Express with TypeScript.
I have a function and it make a query in a database via a Objection.model

const getByIdOrName = (nameUser: any, fullNameUser: any, objectOfModel: any):any => {
    objectOfModel.where((builder: any) => {
      builder.orWhere('name', 'like', nameUser);
      builder.orWhere('fullName', 'like', fullNameUser);
    return objectOfModel

Here bellow is my test with jest:

 it('Should the where and orWhere functions be called', () => {
    const userName = 'Test Mock';
    const fullNameUser= 'Test Full Mock';
    const objectOfModel = {
      where: jest.fn(),
      orWhere: jest.fn()

    getByIdOrName(userName, fullNameUser, objectOfModel);

I would like to know how can I test the orWhere function.
When I run the test, it fails because the orWhere function has expected number of calls:1 and it has received number of calls: 0


The issue is that you’re directly mocking the where and orWhere methods, but your getByIdOrName function doesn’t call them directly. Instead, it calls these methods on the builder object within the where function. Also orWhere is not really being called once in this case, is it?

it('Should the where and orWhere functions be called', () => {
    const userName = 'Test Mock'
    const fullNameUser = 'Test Full Mock'

    // Mock the builder object and its methods
    const builder = {
        orWhere: jest.fn(),

    // Mock the where function to return the builder object
    const whereMock = jest.fn((callback) => {
        return objectOfModel; // Return the objectOfModel for chaining

    // Create the objectOfModel mock
    const objectOfModel = {
        where: whereMock,

    getByIdOrName(userName, fullNameUser, objectOfModel)

    // Verify that the functions were called

Answered By – Nazrul Chowdhury

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published