英文:
How test a function inside of callback with jest
问题
我的应用程序是一个使用TypeScript编写的Express应用程序。
我有一个函数,它通过Objection.model在数据库中进行查询。
以下是我的jest测试:
它应该调用where和orWhere函数。
当我运行测试时,它失败了,因为orWhere函数的期望调用次数为1,但实际调用次数为0。
英文:
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);
expect(objectOfModel.where).toHaveBeenCalledTimes(1);
expect(objectOfModel.orWhere).toHaveBeenCalledTimes(1);
});
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
答案1
得分: 1
问题在于你直接模拟了where和orWhere方法,但是你的getByIdOrName函数并没有直接调用它们。相反,它在where函数内部调用了这些方法。此外,在这种情况下,orWhere实际上并没有被调用一次,对吗?
it('where和orWhere函数应该被调用', () => {
const userName = 'Test Mock'
const fullNameUser = 'Test Full Mock'
// 模拟builder对象及其方法
const builder = {
orWhere: jest.fn(),
}
// 模拟where函数以返回builder对象
const whereMock = jest.fn((callback) => {
callback(builder);
return objectOfModel; // 为了链式调用返回objectOfModel
})
// 创建objectOfModel的模拟
const objectOfModel = {
where: whereMock,
}
getByIdOrName(userName, fullNameUser, objectOfModel)
// 验证这些函数是否被调用
expect(objectOfModel.where).toHaveBeenCalledTimes(1)
expect(builder.orWhere).toHaveBeenCalledTimes(2)
})
英文:
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) => {
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)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论