jeudi 28 avril 2016

Test Express Route in Nodejs with mocked Restler

I am very new to NodeJS.I need some help testing a simple API i have build with Express.

I have the following route in my API:

router.get('/execute', function(req, res, next) {
console.log("Execute Request Query: %s", util.inspect(req.query, false, null));

// Validate Reqest. gremlin is Mandatory field 
if (req == null || req.query.gremlin == null) {
    res.status(400).send(getErrorResponse("Invalid Request", "Request is missing mandatory field: gremlin"));
    return;
}

queryDB(req.query.gremlin, res);
});

This Route calls a shared method queryDB which is making an API call to the Titan DB using its Restful Interface. I am using node_module Restler to make this API Call.

function queryDB(query, res) {
console.log("Constructed Gremlin Query: %s. Querying Titan with URL: %s", util.inspect(query, false, null), titanBaseUrl);

rest.postJson(titanBaseUrl,
    { gremlin: query },
    { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }
).on('complete', function(data, response) {
    if (response != null && response.rawEncoded != null && response.statusCode / 100 == 2) {
        console.log("Call successful. Response.rawEncoded: %s", util.inspect(response.rawEncoded, false, null));
        res.send(getResult(response));
    } else {
        console.error("Call failed. Response: %s", util.inspect(response, false, null));
        res.status(500).send(getErrorResponse("Bad Gremlin Response", response));
    }
});
}

Now, I want to test my API's "execute" endpoint. I am able to do this with following:

var www = require("../bin/www");
var superagent = require('superagent');
var expect = require('expect.js');
var proxyquire = require('proxyquire');

describe('server', function() {

before(function() {
    www.boot();
});

describe('Execute', function() {
    it('should respond to GET', function(done) {
        superagent
            .get('http://localhost:' + www.port + "/gremlin/execute?gremlin=99-1")
            .end(function(err, res) {
                expect(res.status).to.equal(200);
                expect(res.body.data[0]).to.equal(98);
                done()
            })
    })
});

after(function() {
    www.shutdown();
});
});

However I am currently making call to my database which I need to mock. I saw some examples online that help you mock node modules that I could use to mock "Restler". However since I am testing an API by calling the endpoint, I am not sure how to mock a module for this.

I looked at the following examples: http://ift.tt/24nt8Bm http://ift.tt/1rlUHNo etc.

Any help or suggestion is appreciated. Thanks.

Aucun commentaire:

Enregistrer un commentaire