I'm trying to write a test for simple middlware function I'm implementing.// middlewareconst Joi = require('joi');module.exports = (req, res, next) => {const schema = Joi.object().keys({memberId: Joi.string().required()});Joi.validate(req.body, schema, (err, value) => {if (err) {return next(err);}next();});};// passing test when memberId is OKtest("Schema should be valid", () => {const req = {body: {memberId: "MID 12345"}};const res = {}const next = jest.fn();validateSchema(req, res, next);expect(next).toHaveBeenCalled();expect(next).toHaveBeenCalledTimes(1);expect(next).toBeCalledWith();});I'm having issues writing failing test when memberId param is not found. For example:const req = {body: {blahId: "MID 12345"}};I would like to write a test to confirm that next(err) has been called but I'm having no luck connecting the dots: For example,test("Schema should be valid", () => {const req = {body: {fakeId: "MID 12345"}};const res = {}const next = jest.fn();validateSchema(req, res, next);expect(next).toHaveBeenCalled();expect(next).toHaveBeenCalledTimes(1);// How do I test if next has been called with err and how could I assert against property of err object.expect(next).toBeCalledWith(err);});If I change my middleware to callnext(err.details)thenexpect(next).toBeCalledWith([{ "context": { "key": "memberId", "label": "memberId" }, "message": "\"memberId\" is required", "path": ["memberId"], "type": "any.required" }]);works fine however this doesn't seem/feel right.I also have a global error handler that looks like thisapp.use((err, req, res, next) => {console.log(err);if (err.name === 'UnauthorizedError') {return res.status(401).send();}res.status(err.code || 500).send(err);});Thank you.
Submitted November 25, 2018 at 07:15PM by roboctocat
No comments:
Post a Comment