在远程URL上重用Supertest测试

Sha*_*ell 11 mocha.js node.js supertest

我正在使用MochaJSSuperTest在开发过程中测试我的API并且非常喜欢它.

但是,在将代码推送到生产环境之前,我还希望将这些相同的测试转换为远程测试我的临时服务器.

有没有办法通过远程URL或远程URL代理提供请求?

这是我使用的测试样本

        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();
        });
Run Code Online (Sandbox Code Playgroud)

zem*_*rco 17

我不确定你是否可以用超级优惠做到这一点.你绝对可以用superagent来做.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();
      })
  })
})
Run Code Online (Sandbox Code Playgroud)

所以你不能直接使用你现有的测试.但他们非常相似.如果你添加

var app = require('../app.js');
Run Code Online (Sandbox Code Playgroud)

通过更改host变量,您可以轻松地在测试本地应用程序和远程服务器上的部署之间切换

var host = 'http://localhost:3000';
Run Code Online (Sandbox Code Playgroud)

编辑:

刚刚在docs# examples中找到了supertest的一个例子

request = request.bind(request, 'http://localhost:5555');  // add your url here

request.get('/').expect(200, function(err){
  console.log(err);
});

request.get('/').expect('heya', function(err){
  console.log(err);
});
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个问题已经改变,因为这个问题是最后一个回答,但你可以简单地使用带有绝对url /前缀的`supertest`构造函数:`request = supertest('http:// localhost:8080/api'); request.GET中(...` (10认同)

Fer*_*ras 9

您已经提到了它,因为您的目标是远程 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();
});
Run Code Online (Sandbox Code Playgroud)

  • 这是现在这个问题最正确的答案。只需将 URL 添加到“supertest”构造函数就足以将测试指向该 URL。 (2认同)