mercredi 14 avril 2021

How do I create a test for my services controller (Jest)?

I'm trying to create a test for my Animals List Services Controller, making sure the database query is tested. Right now with what I have, I have been able to mock the database query call to ensure the query is being called with the right parameters. However, i'm also trying to mock the return values from the database query call. I'm not sure how to mock dbResult in "services.ts" to get the rows property. Please I need some help, not sure how to do it. Thank you in advance.

I believe I was able to mock the database query call, however, is there a way to refactor or create a test to mock the return call of dbResult?

services.ts

import db from '../../modules/db';
import { DBGenericDataResponse } from '../../types/models';

export async function GetAnimalsList(): Promise<DBGenericDataResponse> {
    const lQuery = `select animalid, description from animal where active=1 order by sortorder, description`;
    const responseMessage: DBGenericDataResponse = {
        code: 200,
        status: 'ok',
        message: '',
        count: 0,
        data: [],
        error: ''
    };
    try {
        const dbResult = await db.query<any>(lQuery);
        responseMessage.message = 'Animals Returned';
        responseMessage.count = dbResult.rows.length;
        responseMessage.data = dbResult.rows;
    } catch (err) {
        responseMessage.code = 400;
        responseMessage.status = 'error';
        responseMessage.message = 'Error retrieving Animals List';
        responseMessage.error  = err;
    }
    return responseMessage;
}

ServicesTest.spec.ts

import * as Services from '../../../../src/controllers/animals/services;
import db from '../../../../src/modules/db';


describe('GetAnimalsList', () => {
   afterEach(() => {
      jest.resetAllMocks();
   });

   it('should call the database with the correct query parameter', async () => {
      const dbMock = jest.spyOn(db, 'query');

      const response = await Services.GetAnimalsList();

      expect(dbMock).toBeCalled();
      expect(dbMock).toHaveBeenCalledWith(
         'select animalid, description from animal where active=1 order by sortorder, description'
      );
   });
});

Aucun commentaire:

Enregistrer un commentaire