Reputation: 61
as you know typeorm find options, and specifically findAndCount, has a where option which takes a query builder as you can see in the docs. it's really easy to user and create your custom query with it's query builder but the testing of it and mocking it, that is something i couldn't figure out how to do it. so the this is how i used it :
const options: FindManyOptions<UserEntity> = {
join: {
alias: 'User',
innerJoinAndSelect: {
userLogin: 'User.userLogin',
payment: 'User.payment',
},
},
where: (queryBuilder: SelectQueryBuilder<UserEntity>) => {
queryBuilder.andWhere(`${queryBuilder.alias}.isManual = 1`);
if (!filters) {
return;
}
if (filters.id) {
queryBuilder.andWhere(`${queryBuilder.alias}.id = :id`, { id: filters.id });
}
if (filters.userId) {
queryBuilder.andWhere(`${queryBuilder.alias}.userId = :userId`, { userId: filters.userId });
}
},
skip: paginationDto.skip,
take: paginationDto.size,
};
options.order = { createdAt: 'DESC' };
const [users, total] = await this._transactionOnlineRepository.findAndCount(options);
and this is how i tried to mock it :
Const fakeQueryBuilder= {
join: jest.fn().mockReturnThis(),
where: (p)=> p.whereFactory(<SelectQueryBuilder<UserEntity>>{
andWhere: jest.fn().mockReturnThis();
})}
const fakeUserRepo = {
findAndCount : jest.fn(()=>fakeQueryBuilder)
};
do you have any idea how to mock this or how to check if my filters are applied?
Upvotes: 1
Views: 1860
Reputation: 11
const returnMock = 'test';
const subQueryMock = {
select: jest.fn().mockReturnThis(),
from: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
subQuery: jest.fn().mockReturnThis(),
getQuery: jest.fn().mockReturnValue(returnMock)
};
const createQueryBuilderMock = {
select: jest.fn().mockReturnThis(),
addSelect: jest.fn().mockReturnThis(),
innerJoin: jest.fn().mockReturnThis(),
innerJoinAndMapOne: jest.fn().mockReturnThis(),
where: jest.fn().mockReturnThis(),
andWhere: jest.fn(function (cb) {
if (typeof cb === 'function') {
cb(subQueryMock);
}
return this;
}),
setParameters: jest.fn().mockReturnThis(),
cache: jest.fn().mockReturnThis(),
insert: jest.fn().mockReturnThis(),
values: jest.fn().mockReturnThis(),
orIgnore: jest.fn().mockReturnThis(),
offset: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
orderBy: jest.fn().mockReturnThis(),
getMany: jest.fn().mockReturnValue(returnMock),
getManyAndCount: jest.fn().mockReturnValue(returnMock),
execute: jest.fn().mockReturnValue(returnMock)
};
I had a similar problem, I needed to mock subQuery, which I've solved like this. notice that mockReturnThis rewrite your instance
Upvotes: 1