Node.js 在远程URL上重用Supertest测试
我正在开发过程中使用和测试我的API,我非常喜欢它 然而,在将代码推出生产环境之前,我还希望将这些测试用于远程测试我的登台服务器 有没有办法为请求提供远程URL或远程URL的代理? 这是我使用的一个测试示例Node.js 在远程URL上重用Supertest测试,node.js,mocha.js,supertest,Node.js,Mocha.js,Supertest,我正在开发过程中使用和测试我的API,我非常喜欢它 然而,在将代码推出生产环境之前,我还希望将这些测试用于远程测试我的登台服务器 有没有办法为请求提供远程URL或远程URL的代理? 这是我使用的一个测试示例 request(app) .get('/api/photo/' + photo._id) .set(apiKeyName, apiKey) .end(function(err, res) { if (er
request(app)
.get('/api/photo/' + photo._id)
.set(apiKeyName, apiKey)
.end(function(err, res) {
if (err) throw err;
if (res.body._id !== photo._id) throw Error('No _id found');
done();
});
我不确定你能不能用supertest来做。你绝对可以用它。Supertest是建立在superagent上的。例如:
var request = require('superagent');
var should = require('should');
var agent = request.agent();
var host = 'http://www.yourdomain.com'
describe('GET /', function() {
it('should render the index page', function(done) {
agent
.get(host + '/')
.end(function(err, res) {
should.not.exist(err);
res.should.have.status(200);
done();
})
})
})
因此,您不能直接使用现有的测试。但它们非常相似。如果你加上
var app = require('../app.js');
在测试的顶部,通过更改host
变量,您可以轻松地在测试本地应用程序和远程服务器上的部署之间切换
var host = 'http://localhost:3000';
编辑:
刚刚在
您已经提到了,因为您的目标是远程URL,所以只需将应用程序替换为您的远程服务器URL即可
request('http://yourserverhere.com')
.get('/api/photo/' + photo._id)
.set(apiKeyName, apiKey)
.end(function(err, res) {
if (err) throw err;
if (res.body._id !== photo._id) throw Error('No _id found');
done();
});
其他答案对我不适用 他们使用
.end(function(err,res){
这是任何异步http调用的问题,需要使用。然后改为使用:
示例工作代码如下所示:
文件:\test\rest.test.js
文件:\package.json
安装并运行
我想你已经了解了一些事情。让我做一些测试,如果成功了,我会接受。谢谢。我假设这自上次回答这个问题以来已经发生了变化,但是你可以简单地使用带有绝对url/前缀的supertest
构造函数:request=supertest('http://localhost:8080/api“);request.get(…
这是对这个问题最正确的答案。只需将URL添加到超级测试
构造函数中,就足以将测试指向该URL。
request('http://yourserverhere.com')
.get('/api/photo/' + photo._id)
.set(apiKeyName, apiKey)
.end(function(err, res) {
if (err) throw err;
if (res.body._id !== photo._id) throw Error('No _id found');
done();
});
let request = require("supertest");
var assert = require("assert");
describe("Run tests", () => {
request = request("http://localhost:3001"); // line must be here, change URL to yours
it("get", async () => {
request
.get("/") // update path to yours
.expect(200)
.then((response) => { // must be .then, not .end
assert(response.body.data !== undefined);
})
.catch((err) => {
assert(err === undefined);
});
});
});
"devDependencies": {
"supertest": "^6.1.3",
"mocha": "^8.3.0",
},
"scripts": {
"test": "mocha"
}
npm i
npm test