【问题标题】:Supertest Expect Not Asserting Status Codes Correctly超测期望未正确断言状态代码
【发布时间】:2016-06-09 14:46:39
【问题描述】:

我有一个看起来像这样的测试:

  it('should fail to get deleted customer', function(done) {
    request(app)
      .get('/customers/'+newCustomerId)
      .set('Authorization', 'Bearer ' + token)
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(404, done)
  });

我已经阅读了这里的文档:

https://github.com/visionmedia/supertest

上面写着:

注意如何将 done 直接传递给任何 .expect() 调用

不起作用的代码行是.expect(404, done),如果我将其更改为.expect(200, done),那么测试不会失败。

但是,如果我添加这样的结尾:

  it('should fail to get deleted customer', function(done) {
    request(app)
      .get('/customers/'+newCustomerId)
      .set('Authorization', 'Bearer ' + token)
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
          if (err) console.log(err);
          done();
      });
  });

然后测试失败。为什么.expect(200, done) 也没有失败?

【问题讨论】:

    标签: node.js jasmine supertest


    【解决方案1】:

    根据文档,这是符合预期的。 (https://github.com/visionmedia/supertest)

    如果您使用 .end() 方法 .expect() 失败的断言不会抛出 - 它们会将断言作为错误返回给 .end() 回调。为了使测试用例失败,您需要重新抛出或将 err 传递给 done()

    当您同步进行断言时,您有义务手动处理错误。在您的第一个代码 sn-p 中,.expect(404, done) 永远不会被执行,因为在它到达之前抛出了一个异常。

    您的第二个 sn-p 按预期失败,因为它能够处理错误。由于错误已传递给function(err, res) {} 处理程序。

    我发现必须以这种方式处理错误很麻烦,而且几乎是弄巧成拙。所以更好的办法是使用promise,这样错误就可以自动处理如下:

    it('should fail to get deleted customer', function() {
      return request(app)
        .get('/customers/'+newCustomerId)
        .set('Authorization', 'Bearer ' + token)
        .set('Accept', 'application/json')
        .expect('Content-Type', /json/)
        .expect(200); 
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 2015-11-30
    • 2012-03-28
    相关资源
    最近更新 更多