I am using typeorm Brackets as follows:
const getQuery = this.repository.createQueryBuilder("user");
const brackets = new Brackets((qb) => {
qb.where("user.name ~* :name", { name: "aaa" });
qb.orWhere("user.name.~* :name", {
name: "bbb",
});
});
getQuery.andWhere(brackets);
const result = (await getQuery.getMany());
How can I test it properly in unit test? I think the real concern is the Bracket method, can we just test it as a normal function like:
expect(repository.andWhere).toHaveBeenNthCalledWith(new Brackets((qb) => {
qb.where("user.name ~* :name", { name: "aaa" });
qb.orWhere("user.name ~* :name", {
name: "bbb",
});
}));
The error I got was: on the service, not too sure how I can test it properly: TypeError: qb.where is not a function
I recently stuck on this too. What I did was mock the typeorm Brackets class and the callback functions, so that we could spy on the called functions.
const bracketsMock = {
where: jest.fn().mockReturnThis(),
orWhere: jest.fn().mockReturnThis(),
};
jest.mock('typeorm', () => {
return {
...jest.requireActual('typeorm'),
Brackets: jest.fn(function(cb) {
cb(bracketsMock)
})
};
});
then we spy on the brackets callback:
const bracketWhereSpy = jest.spyOn(bracketsMock, 'where');
const bracketOrWhereSpy = jest.spyOn(bracketsMock, 'orWhere');
expect(bracketWhereSpy).toHaveBeenCalled();
expect(bracketOrWhereSpy).toHaveBeenCalled();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With