我对 NodeJS 很陌生。我需要一些帮助来测试我用 Express 构建的简单 API。
我的 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);
});
此路由调用共享方法 queryDB,该方法使用其 Restful 接口(interface)对 Titan DB 进行 API 调用。我正在使用 node_module ReSTLer 进行此 API 调用。
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));
}
});
}
现在,我想测试 API 的“执行”端点。我可以通过以下方式做到这一点:
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();
});
});
但是我目前正在调用我需要模拟的数据库。我在网上看到了一些示例,可以帮助您模拟 Node 模块,我可以用它们来模拟“ReSTLer”。但是,由于我通过调用端点来测试 API,因此我不确定如何为此模拟模块。
我查看了以下示例: https://stackoverflow.com/a/33773233/2596762 https://www.terlici.com/2015/09/21/node-express-controller-testing.html 等等
如有任何帮助或建议,我们将不胜感激。谢谢。
最佳答案
我能够使用 this SO answer 模拟的下游系统来测试我的 API .
但是我不确定这是否是最好/唯一的方法。
关于node.js - 使用模拟模块在 Nodejs 中测试 Express Route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36926396/