【问题标题】:Mocha Does Not Fail When Tests Wrapped in describe()当测试包含在 describe() 中时,Mocha 不会失败
【发布时间】:2016-08-22 14:55:00
【问题描述】:

我有相对简单的 mocha & chai 测试设置。不幸的是,当我运行 mocha 时,肯定会失败的测试通过了!这是我的测试用例。

var expect = require('chai').expect;
var nock = require('nock');
var request = require('request');

var testUrl = 'http://test.wicked.ti';
var getItems = function(url, callback) {               
     request.get(url + '/items',function(err, data) {
     if(err) throw err;
     callback(data);
  });
};

describe('Sample Unit Tests', function(){
  it('I am making sure the correct rest endpoint is called', function() {
    var request = nock(testUrl)
      .get('/items')
      .reply(200, {});

    getItems(testUrl, function(data) {
      console.log(data);            // This runs
      expect(true).to.equal(false);  // This should always fail!
      done();
    });  
  });
});

expect(true).to.equal(false) 包装在try catch 中会引发一个错误(如下所示),该错误会被很好地捕获。那就是

   it('I am making sure the correct rest endpoint is called', function() {
    var request = nock(testUrl)
      .get('/items')
      .reply(200, {});

    getItems(testUrl, function(data) {
      console.log(data);            // This runs

      // Adding try/catch block
      try { expect(true).to.equal(false); } catch(err) { console.error(err) } 

      done();
    });  

这是记录的错误

{ [AssertionError: expected true to equal false]
  message: 'expected true to equal false',
  showDiff: true,
  actual: true,
  expected: false }

我一直在绞尽脑汁想弄清楚我可能做错了什么而没有成功!问题是我错过了什么?如果有任何帮助,我试图在describe()it() 块之外写这个,它运行得很好。

【问题讨论】:

  • 试试it('something', function(done){ ... ?

标签: javascript unit-testing mocha.js


【解决方案1】:

这是因为您正在运行同步测试,因此它不会等待异步函数完成。要使其异步,您的回调需要一个参数:

it('...', function(done) {
  //                 |
  //                 |
  //        this is where "done" comes from and it's
  //         the missing bug in your code

【讨论】:

  • 谢谢!这是我遗漏的一个小细节。我没有意识到我需要传递 done 参数。它记录在哪里?
  • @Willa:mochajs.org/#asynchronous-code。很容易错过。有趣的事实:大多数人不知道所有函数都有一个.length 属性,该属性反映了函数定义为具有多少个参数。我在我编写的库中使用它来计算要传递给回调的值。 Mocha 使用相同的机制来确定测试是同步还是异步。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 2018-01-03
  • 1970-01-01
相关资源
最近更新 更多