TypeError: callback is not a function. How to transform this mocha test to async testing?

23 Views Asked by At

This is a simple web application which manages resources. I am using MongoDB and Mongoose for database and I am trying to test the findOne() mongoose function. It takes a property as a parameter and finds the entity that fits the requierment. Now my teacher who teaches the Mocha for testing uses a video that's 5-6 years old. And since then mongoose changed and so did Mocha. My testing code is right here and below that is my middleware which I test.

Test

const expect = require('chai').expect;
const getResourceMW = require('../../../../middleware/Resource/getResourceMW');

describe('getResourceMW middleware ', function () {

    it('should return resource', function (done) {
        const mw = getResourceMW({
            ResourceModel: {
                findOne:(p1,cb)=>{                             //<------- THIS PART
                    cb(null,'mock resource')
                }
            }
        });

        mw({
            params:{
                resourceid : '42'
        }
        },{
            locals:{

            }
        },()=>{
            done();
        })
    });
});

Middleware

const requireOption = require('../requireOption');

module.exports = function(objectRepository) {
    const ResourceModel = requireOption(objectRepository,'ResourceModel');

   return function (req,res,next){
       ResourceModel.findOne({_id: req.params.resourceid})
           .then(function(resource){
               res.locals.resource = resource;
               return next();
           })
           .catch(function (err){
               console.log(err);
               return next(err);
           });
   }
};

And the error is this:

mocha .\getResourceMW.js

getResourceMW middleware 1) should return resource

0 passing (5ms) 1 failing

  1. getResourceMW middleware should return resource: TypeError: cb is not a function

Mongoose now uses the findOne with not a callback, but .then as you can see in my code. How should I change my test code(the first one, where the comment arrow is) so that I can test the findOne function of mongoose?

0

There are 0 best solutions below