如何用jest测试回调函数

dfddblmv  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(146)

我的应用程序是一个带TypeScript的Express。我有一个函数,它通过Objec.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
}

下面是我的玩笑测试:

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);
    expect(objectOfModel.where).toHaveBeenCalledTimes(1);
    expect(objectOfModel.orWhere).toHaveBeenCalledTimes(1);
 });

我想知道如何测试orWhere函数。当我运行测试时,它失败了,因为orWhere函数的预期调用次数为1,而它收到的调用次数为:0

guicsvcw

guicsvcw1#

问题是您直接模拟了where和orWhere方法,但getByIdOrName函数并不直接调用它们。相反,它在where函数内的构建器对象上调用这些方法。Also或Where在这种情况下并没有真正被调用一次,是吗?

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) => {
        callback(builder);
        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
    expect(objectOfModel.where).toHaveBeenCalledTimes(1)
    expect(builder.orWhere).toHaveBeenCalledTimes(2)
})

相关问题