我正在创建一个小的Node.js应用程序,它使用Superagent(v5.1.2)调用一些REST api。我需要发送带有get请求的过滤器选项。
API端点需要以下结构:
endpoint-url / test?filter = _name eq'testname'
我正努力通过内置查询方法使用superagent来实现此结果。当我发送请求时,我将退回所有物品,因此filter选项没有任何效果。通过邮递员对其进行测试后,我将只获得带有_name = 'testname'
返回的指定商品。
这是我的代码段
let name = 'testname';
superagent.get('endpoint-url/test')
.authBearer(token)
.query({'filter': '_name eq ' + name})
.then(res => {
...
})
.catch(err => {
...
});
答案 0 :(得分:0)
这是一个最小的工作示例:
app.js
:
const express = require("express");
const app = express();
const memoryDB = {
users: [{ name: "testname" }, { name: "haha" }],
};
app.get("/test", (req, res) => {
console.log(req.query);
const filterName = req.query.filter.split("eq")[1].trim();
const user = memoryDB.users.find((user) => user.name === filterName);
res.status(200).json(user);
});
module.exports = app;
app.test.js
:
const app = require("./app");
const superagent = require("superagent");
const { expect } = require("chai");
describe("59246379", () => {
let server;
before((done) => {
server = app.listen(3003, () => {
console.info(`HTTP server is listening on http://localhost:${server.address().port}`);
done();
});
});
after((done) => {
server.close(done);
});
it("should pass", () => {
let name = "testname";
return superagent
.get("http://localhost:3003/test")
.query({ filter: "_name eq " + name })
.then((res) => {
expect(res.status).to.be.equal(200);
expect(res.body).to.be.eql({ name: "testname" });
});
});
});
具有覆盖率报告的集成测试结果:
59246379
HTTP server is listening on http://localhost:3003
{ filter: '_name eq testname' }
✓ should pass (46ms)
1 passing (57ms)
-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
app.js | 100 | 100 | 100 | 100 | |
app.test.js | 100 | 100 | 100 | 100 | |
-------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59246379