Tuesday, 2 May 2017

node mongoose mocha How to debug a failing mongoose test?

I have the following model

MODEL const Schema = mongoose.Schema;

    const Privilege = new Schema({
      privilege: {
        table_id: {
          type: String,
          required: false
        },
        canWrite: {
          type: Boolean,
          required: true,
          default: false
        }
      }
    });
    const UserSchema = new mongoose.Schema({
      username: {
          type: String,
          required: true
      },
      ...
      privileges: [Privilege]
      ...

I am testing with the following Mocha/Chai test

    TEST
      const newWritePrivilege = { privilege: { user_id: '56z787zzz67fc', canWrite: true }};

     .post(`/api/v1/users/${user._id}/privileges`)
             .send(newWritePrivilege)
             .expect(httpStatus.OK)

withe the following route

router.route('/:userId/privileges')
   .post(userCtrl.grantPrivilege);

and the following Controller function

    function grantPrivilege(req, res, next) {
      console.log('GRANT PRIVILEGE: %j TO USER %j', req.body, req.params.userId);
      User.findOneAndUpdate({ _id: req.params.userId }, { $push: { privilege: req.body } }, { new: true })
        .then(savedUser => res.json(savedUser))
        .catch((e) => {
          console.log('ERROR: ', e);
          next(e);
        });
    }

I get the following display in the console, the privilege is not pushed into the array

 GRANT PRIVILEGE: {"privilege":  
    {"user_id":"56z787zzz67fc","canWrite":true}} TO USER "5908f5439a6c3a279e3909cd"
 user:    
  {"__v":0,"username":"KK123","password":"KKpassword",
  "email":"kk123@example.com","mobileNumber":"9999999999",
  "_id":"5908f5439a6c3a279e3909cd",
  "createdAt":"2017-05-02T21:08:19.283Z","privileges":[]}

user.privileges array is still empty

I have been doing it for another test for permissions, and quite duplicated the code , but this time it's not working... How can I debug it and get some addition error info ?

thanks for feedback



via erwin

No comments:

Post a Comment