Reputation: 149
I have this function in my controller:
async save(req: Request, res: Response) {
try {
const user = new User();
user.nome = 'Jhon Doe';
const admin = new Morador;
admin.user = user;
await getManager().transaction( async entity => {
await entity.save(user);
await entity.save(admin);
});
res.status(201).json(admin);
} catch (e) {
res.sendStatus(500);
}
}
I need to mock this function:
await getManager().transaction( async entity => {
await entity.save(user);
await entity.save(admin);
});
I need to receive the input values from the entity.save
function.
How to do this with Jest?
Upvotes: 0
Views: 2332
Reputation: 149
After studying further how the getManager().transaction()
function works, I was able to implement the mock like this:
function mockGetManager(objects: Array<any>) {
async function mockEntityManager() {
const entityManager = {} as EntityManager;
entityManager.save = function save(entity: any): Promise<any> {
// todo
return Promise.resolve(true);
}
entityManager.update = function update(entity: any, update: any): Promise<any> {
// todo
return Promise.resolve(true);
}
entityManager.findOne = function findOne(query: any): Promise<any> {
// todo
return Promise.resolve(true);
}
entityManager.find = function find(query?: any): Promise<Array<any>> {
// todo
return Promise.resolve([]);
}
entityManager.delete = function del(query: any): Promise<any> {
// todo
return Promise.resolve(true);
}
await arguments[0](entityManager);
}
getManager().transaction = jest.fn().mockImplementation(mockEntityManager);
}
The function can be called this way when using:
const saved = [];
mockGetManager(saved);
expect(saved).toHaveLength(numberObjectsSaved);
I thought the solution was good because in this case I needed to test only the logic of the controller, so there is no need to test the transaction, as it is tested in the unit tests of the models.
I hope I can have helped someone.
Upvotes: 1