mardi 17 mars 2020

Testing an express middleware with Jest

I'm trying to test my controller (express middleware) with Jest. In order to explain my problem, I'll provide my code:

import request from 'utils/request';
import logger from 'config/logger';

const get = async (req, res, next) => {
  try {
    const response = await request.get('entries?content_type=category');
    return res.json(response.data);
  } catch (error) {
    logger.error(error.response.data.message);
    return next(error);
  }
};

module.exports = {
  get,
};

I need to test this get function. In order to do so, I need to provide the req, res and next args to it. I've found this question where the op talks about mocking the express request and then says "how to use it" but I can't see how. That's the only topic that I've seen so far directly related with my problem but the answer doesn't work for me (I don't want to use Nock nor any other library to adchieve the testing, just Jest).

So, how can I successfully test this function? Is it by using mocking or is there any other way?

Sorry for my bad english and thanks in advance for your help!

Aucun commentaire:

Enregistrer un commentaire