当测试包含在 describe() 中时,Mocha 不会失败
Mocha Does Not Fail When Tests Wrapped in describe()
我有相对简单的 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();
});
});
});
在 try catch 中包装 expect(true).to.equal(false)
会抛出一个错误(如下所示),该错误被很好地捕获了。即
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('...', function(done) {
// |
// |
// this is where "done" comes from and it's
// the missing bug in your code
我有相对简单的 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();
});
});
});
在 try catch 中包装 expect(true).to.equal(false)
会抛出一个错误(如下所示),该错误被很好地捕获了。即
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('...', function(done) {
// |
// |
// this is where "done" comes from and it's
// the missing bug in your code