mardi 2 mars 2021

Testing Controller and Service in Jest

I'm fairly new to Jest and have been trying (with no luck) to figure out how to write tests for my controller. I'm not sure how to write the test as it calls another function. It would be great if I could get pointed in the right direction at least. Thanks in advance.

controller.ts

import * as Services from './services';

export async function GetCountriesList(req: Request, res: Response): Promise<void> {
    const response = await Services.GetCountriesList();
    res.status(response.code).json({
        status: response.status,
        message: response.message,
        count: response.count,
        data: response.data
     });
}

service.ts

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

export async function GetCountriesList(): Promise<DBGenericDataResponse> {
    const lQuery = 'somquery';
    const responseMessage: DBGenericDataResponse = {
        code: 200,
        status: 'ok',
        message: '',
        count: 0,
        data: [],
        error: ''
    };
    try {
        const dbResult = await db.query<any>(lQuery);
        responseMessage.message = 'Countries returned';
        responseMessage.count = dbResult.rows.length;
        responseMessage.data = dbResult.rows;
    } catch (err) {
        responseMessage.code = 400;
        responseMessage.status = 'error';
        responseMessage.message = 'Error retrieving Countries List';
        responseMessage.error  = err;
    }
    return responseMessage;
}

Aucun commentaire:

Enregistrer un commentaire