简体   繁体   中英

Testing express routes with mongoose query

I am trying to test my routes that have mongoose queries in. I keep getting back:

AssertionError: expected undefined to equal true

Below is the basic template of my test. At the moment I just want to confirm it calles the res.json.

The route returns all entries in the User model

route.js

const User = require('../../../models/users/users');

const listUsers = (req, res) => {
  User.find((err, users) => {
    if (err) res.send(err);

    res.json(users);
  })
};

module.exports = listUsers;

test.js

const expect = require('chai').expect;
const sinon = require('sinon');

const listUsers = require('../../../../src/routes/api/users/listUsers');

describe('listUsers', () => {
  it('retrieves users', () => {
    const req = {};
    const res = {};
    const spy = res.json = sinon.spy;

    listUsers(req, res);
    expect(spy.calledOnce).to.equal(true);
  })
});

The find function takes two parameters. The first one is the criteria for the search and second is the callback function. Looks like you have missed the first parameter.

Since you want to find all users the criteria for you is - {}

So this will solve your problem -

User.find({}, (err, users) => {
    if (err) res.send(err);

    res.json(users);
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM