4

Here is the route I want to test:

app.post('/api/user', (req, res) => {

        dbService.replaceUserOnDuplicate(req.body, function returnResponse(insertedId) {
            if (insertedId === 0 || insertedId === req.body.id) {
                return res.sendStatus(200);                            
            }
            // TODO_MINH: Send an appropriate error to handle by the front-end
            return res.send({});
        });
    });

I can use chai-http to do something like this (psuedo-code):

it('test', function (done) {
            chai.request(server)
                .post('/api/user')
                .send({ user: SomeUserObject })
                .end(function (err, res) {
                    res.should.have.status(200);
                    done();
                });

        });

However, the api/users route makes a Database call. How would I use sinon to stub this method (replaceUserOnDuplicate) so that it returns a dummy response (like 0, or anything)?

Is it possible? I'm looking at the Chai-HTTP syntax and I see no room to insert any Sinon stubbed methods.

For reference, here is the dbService (mySQL node.js):

replaceUserOnDuplicate: function(user, callback) {
        this.tryConnect().getConnection(function(err, con) {
            var sql = queries.ReplaceUserOnDuplicate;
            // Insert parameters
            con.query(sql, [user.id, user.googleID, user.gender, user.firstName, user.lastName, user.email, user.isProfileSetUp, user.location, user.phoneNumber,
                 // On Duplicate Key Update parameters
                 user.googleID, user.gender, user.firstName, user.lastName, user.email, user.isProfileSetUp, user.location, user.phoneNumber], 
                 function (err, result) {
                con.release();
                if (err) throw err;
                return callback(result.insertId);
            });
        });
    },

Thanks for your help!

Minh Lu
  • 79
  • 4
  • What's the db? Does it have a mock that you can inject? – Matt Oct 24 '17 at 05:52
  • Added the relevant db call to the original post. My question is, even if I can mock it, how would that look syntax-wise? How do I inject it? – Minh Lu Oct 24 '17 at 06:10
  • So, I'm currently tackling the same problem. Is the solution you've posted below what you eventually ended up going with? – random_coder_101 Dec 02 '19 at 17:11

1 Answers1

0

A potential solution: if I use middleware to set the property of req.db to our dbService object, then I can dependency inject the dbService's calls within chai-http...By sending them parameters with the .send(). I believe .send() can be chained.

Is this valid?

Example (Middleware):

var exposeDb = function(req, resp, next){
    req.dbService= dbService;
    next();
  };

  app.use('/api/user', exposeDb, next);
Minh Lu
  • 79
  • 4