我正在尝试组合一个基于supertest的集成测试套件(由Mocha运行),以对我们的REST API进行ping操作并验证响应。

但是,我的测试似乎未按预期运行:

var assert = require('assert')
var should = require('should')
var request = require('superagent')

var WEBSERVICE_BASE = 'localhost:8080/our-application/'

describe('Authentication', function() {
  it('prevents user from logging in without credentials', function() {
    console.log('###')
    console.log('Starting with: ' + request)
    console.log('###')
    request.get(WEBSERVICE_BASE + 'auth', function(err, res) {
      console.log('Error: ' + err)
      if (err) {
        throw err
      }
      res.should.have.status(401)
      done()
    })
  })
})


我在控制台中看到的是:

Craigs-MBP:mocha-tests Craig$ ./run.sh


  Authentication
###
Starting with: function request(method, url) {
  // callback
  if ('function' == typeof url) {
    return new Request('GET', method).end(url);
  }

  // url first
  if (1 == arguments.length) {
    return new Request('GET', method);
  }

  return new Request(method, url);
}
###
    ✓ prevents user from logging in without credentials

    1 passing (12ms)


似乎request被重新定义为函数,而不是superagent对象?

该测试不应通过,并且至少应看到打印console.log参数的err

最佳答案

请记住,javascript是异步的。除非您将“ done”参数放在it方法中,否则Superagent会在调用回调之前终止测试:

it('prevents user from logging in without credentials', function(done) {...


测试完成执行,并且在调用回调之前,mocha已终止。

关于javascript - Superagent“请求”对象是否被重新定义为功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28012377/

10-10 09:52