Bragon
Bragon

Reputation: 105

How can I mock up the express-validator withDefaults function using jest?

I am trying to unit test my validation segment which uses express-validator.

This is the code I'm trying to test:

const errorMsgs = require('../lib/error-messages');

const validationResults = validationResult.withDefaults({
  formatter: ({ msg }) => msg,
});

const fieldValidation = [
  body('fullName')
    .trim()
    .notEmpty()
    .withMessage(errorMsgs.mandatoryField),

  body(['yourEmailAddress', 'teamEmailAddress', 'lineManagerEmailAddress'])
    .trim()
    .notEmpty()
    .withMessage(errorMsgs.mandatoryField)
    .isEmail({ host_whitelist: ['dwp.gov.uk', 'engineering.digital.dwp.gov.uk'] })
    .withMessage(errorMsgs.invalidEmailAddr),

  body('slackChannel')
    .optional({ values: 'falsy' })
    .trim()
    .isURL({ host_whitelist: ['dwpdigital.slack.com'] })
    .withMessage(errorMsgs.invalidSlackUrl),

  body('dwpServiceName')
    .trim()
    .notEmpty()
    .withMessage(errorMsgs.mandatoryField),

  body('redirectUrl')
    .trim()
    .notEmpty()
    .withMessage(errorMsgs.mandatoryField)
    .isURL()
    .withMessage(errorMsgs.invalidUrl),

  body(['scopes', 'claims'])
    .notEmpty()
    .withMessage(errorMsgs.mandatoryField)
    .customSanitizer((values) => (values ? values.split(',') : null))
    .trim()
    .isArray()
    .withMessage(errorMsgs.invalidArr),

  (req, res, next) => {
    const errors = validationResults(req);

    if (!errors.isEmpty()) {
      res.locals.errors = errors.mapped();
    }
    return next();
  },
];

module.exports = fieldValidation;


This is my latest stab (of many) at mocking it:

const errorMsgs = require('../../app/lib/error-messages');
const fieldValidation = require('../../app/middleware/field-validation');

jest.mock('express-validator', () => {
  const originalModule = jest.requireActual('express-validator');

  // Mock the withDefaults method
  const withDefaultsMock = jest.fn((options) => ({
    validationResult: jest.fn((req) => {
      const errors = originalModule.validationResult(req);
      // Apply the custom formatter, as defined in the original module
      errors.formatWith = options.formatter;
      return errors;
    }),
  }));

  return {
    ...originalModule,
    withDefaults: withDefaultsMock,
    validationResult: jest.fn(), // Mock validationResult as a function
  };
});

And here's the error I get when I run jest:

TypeError: validationResult.withDefaults is not a function

It appears that express.validator is written in typescript and I've a feeling that's the root of my problem but I really don't know.

Upvotes: 0

Views: 46

Answers (0)

Related Questions