Unit Testing with Express Validator

How can I unit test perform my checks using express validator?

I tried to create the object stub object, but get an error: TypeError: Object #<Object> has no method 'checkBody'. I can manually check if the check works in the application.

Here is what I tried:

describe('couponModel', function () {
    it('returns errors when necessary fields are empty', function(done){
        var testBody = {
            merchant : '',
            startDate : '',
            endDate : ''
        };
        var request = {
            body : testBody
        };
        var errors = Model.validateCouponForm(request);
        errors.should.not.be.empty;
        done();
    });
});

I understand that the method is checkBodyadded to the request object when I have it app.use(expressValidator())in my explicit application, but since I only test that validation works in this unit test, I do not have an instance of the available express application available, and the verification method that I am testing is it is not called directly from it in any case, since it is called only through the mail route, which I do not want to call for unit test, since it is connected with the database operation.

+4
2

- api (v4):

tl; dr: :

exports.testExpressValidatorMiddleware = async (req, res, middlewares) => {
  await Promise.all(middlewares.map(async (middleware) => {
    await middleware(req, res, () => undefined);
  }));
};

:

const { validationResult } = require('express-validator/check');

await testExpressValidatorMiddleware(req, res, expressValidatorMiddlewareArray);
const result = validationResult(req);
expect(result....

async/await. node-mocks-http req res.

:

express-validator . , :

[
  check('addresses.*.street').exists(),
  check('addresses.*.postalCode').isPostalCode(),
]

.

, , express .

, , (next ). next? , , - , .

const loggerMiddleware = (req, res, next) => {
  console.log('req body is ' + req.body);
  next();
  console.log('res status is ' + res.status);
};

express-validator , next() . next().

next, TypeError:

middlewares.map((middleware) => {
  middleware(req, res, () => undefined);
});

, express-validator promises, ...

middlewares.map(async (middleware) => {
  await middleware(req, res, () => undefined);
});

, promises (Mozilla docs Promise.all ):

await Promise.all(middlewares.map(async (middleware) => {
  await middleware(req, res, () => undefined);
}));

:

exports.testExpressValidatorMiddleware = async (req, res, middlewares) => {
  await Promise.all(middlewares.map(async (middleware) => {
    await middleware(req, res, () => undefined);
  }));
};

. - , .

+2

, , :

var validRequest = {
  // Default validations used
  checkBody: function () { return this; },
  checkQuery: function () { return this; },
  notEmpty: function () { return this; },

  // Custom validations used
  isArray: function () { return this; },
  gte: function () { return this; },

  // Validation errors
  validationErrors: function () { return false; }
};

function getValidInputRequest(request) {
    Object.assign(request, validRequest);
    return request;
}

, getValidInputRequest:

describe('couponModel', function () {
  it('returns errors when necessary fields are empty', function(done){
      var testBody = {
          merchant : '',
          startDate : '',
          endDate : ''
      };
      var request = {
          body : testBody
      };

      request = getValidInputRequest(request); // <-- Update the request

      var errors = Model.validateCouponForm(request);
      errors.should.not.be.empty;
      done();
  });
});

request body , -.

, , - :

function getInvalidInputRequest(request, errorParams) {
    // Get de default valid request
    Object.assign(request, validRequest);

    // Override the validationErrors function with desired errors
    request.validationErrors = function () {
        var errors = [];
        errorParams.forEach(function(error){
            errors.push({msg: 'the parameter "'+ error +'" is mandatory'})
        });
        return errors;
    };
    return request;
}

, :

request = getInvalidInputRequest(request, ['mandatory_param_1', 'mandatory_param_2']);
+1

All Articles