Issue
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
Solution
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)
})
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