我正在尝试使用Mocha 2.4.5和Should.js 8.3.0在浏览器中设置测试。
失败断言是否应该显示有用的测试失败原因
但是,当在jQuery Ajax回调的上下文中进行相同的断言时,我会得到一个未捕获断言错误。
举以下例子:
mocha.setup('bdd');
var url = 'http://localhost/api/v2/People';
describe('ajax', () => {
var that1 = this;
it('Passing async assertion', (done) => {
$.ajax({ url: url }).done(data => {
should(1).be.eql(1);
done();
});
});
it('Failing async assertion', (done) => {
var that2 = this;
$.ajax({ url: url }).done(data => {
should(0).be.eql(1);
done();
});
});
it('Failing sync assertion', (done) => {
should(0).be.eql(1);
done();
});
});
mocha.run();
"传递异步断言"在测试运行程序输出中传递并看起来很漂亮。
"失败的同步断言"失败,我得到了一个有用的堆栈跟踪
失败同步断言⑪
断言错误:应为0等于1
在Assertion.fail(http://path/to/should.js:220:17)
位于Assertion.Object.defineProperty.value(http://path/to/should.js:292:19)
在Context。(tests.js:337:26)
但是,"Failing async assertion"会失败(这很好),但堆栈竞争是无usless的。
异步断言失败?
错误:未捕获断言错误(http://path/to/should.js:200)
我曾尝试将ajax上下文设置为that1或that2,但这没有什么区别。
是否有其他方法可以格式化测试用例,使异步断言发挥作用?
编辑
我用一个简单的超时来模拟异步得到了同样的结果
mocha.setup('bdd');
describe('ajax', () => {
var that1 = this;
it('Failing async assertion', (done) => {
setTimeout(() => {
should(0).be.eql(1);
done();
}, 100);
}).async = true;
it('Failing sync assertion', (done) => {
should(0).be.eql(1);
done();
});
});
mocha.run();
Mocha的文档建议格式化异步测试,正如我在问题中所做的那样,但我认为这些文档是在考虑Node.js测试运行程序的情况下编写的。
在浏览器中,似乎有必要在"before"函数中执行异步代码,然后根据存储的值进行同步断言。
例如:
mocha.setup('bdd');
describe('ajax', () => {
var value = 0;
before((done) => {
//Do the asynchronous bit
setTimeout(() => {
//store the value for later comparison
value = 1;
done();
}, 100);
});
//These wont be called until after done() is called above.
//So value will be 1
it('Failing assertion', () => {
should(value).be.eql(0);
});
it('Passing assertion', () => {
should(value).be.eql(1);
});
});
mocha.run();
这里的额外好处是Mocha不会因为外部因素(如网络延迟)而将异步断言标记为缓慢。