我想为异步进程创建单元测试。我创建了一个简单的情况模拟,使用超时来延迟警报。 (真正的过程是动态加载 JS 文件)。
我刚刚开始介绍 Mocha 、 Chai 和西农。我在 HTML 文件旁边创建了一个名为 vendor
的文件夹。其中包含最新版本的 mocha.css、mocha.js、chai.js 和 sinon.js。
如果我注释掉 setTimeout()
调用,下面的代码可以正常工作。我应该如何更改它,以便 sinon.assert...
调用将等待延迟操作发生?
<!DOCTYPE html>
<head>
<title>Delayed alert test</title>
</head>
<body>
<div id="mocha"><p><a href=".">Index</a></p></div>
<div id="messages"></div>
<div id="fixtures"></div>
<link rel="stylesheet" type="text/css" href="vendor/mocha.css" />
<script src="vendor/mocha.js"></script>
<script src="vendor/chai.js"></script>
<script src="vendor/sinon.js"></script>
<script>
mocha.setup('bdd')
var spy = sinon.spy(window, 'alert')
describe("Test", function() {
describe("#alert", function() {
it("should show an alert", function(done) {
this.timeout(5000)
setTimeout(function () { // Works if these 2 lines...
alert ("Once")
alert ("Twice")
}, 2000) // are commented out
sinon.assert.called(spy)
sinon.assert.calledTwice(spy)
sinon.assert.calledWithExactly(spy, "Once")
sinon.assert.calledWithExactly(spy, "Twice")
done()
});
});
})
mocha.run();
</script>
</body>
</html>
最佳答案
一旦设置超时,就会调用您的断言和 done()
(如果测试到达那里)。
测试设置超时
this.timeout(5000)
安排您的测试在 2 秒内运行,然后立即继续。
setTimeout(...
检查失败的断言
sinon.assert.called(spy)
然后在 setTimeout
有机会运行之前退出。
断言需要在 setTimeout 完成后运行,并且当我们在浏览器中时,需要在 try/catch block 中捕获异步断言,以便实际的异常可以通过 done( )
。
大多数异步 API 允许您传入一个“回调”函数,该函数在异步任务完成后调用,这通常是您放入断言/完成的函数。
就你而言,它更字面化一点......
describe("Test", function() {
describe("#alert", function() {
it("should show an alert", function(done) {
this.timeout(5000)
var stub = sinon.stub(window, 'alert')
var assertion = function(){
try {
sinon.assert.called(stub)
sinon.assert.calledTwice(stub)
sinon.assert.calledWithExactly(stub, "Oce")
sinon.assert.calledWithExactly(stub, "Twice")
done()
} catch ( e ) {
done( e )
}
}
setTimeout(function () {
alert ("Once")
alert ("Twice")
assertion()
}, 2000)
});
});
})
https://jsfiddle.net/6w4p7rxz/
请注意,我将 spy
更改为 stub
以减少点击次数。还可以使用 chai !也许sinon-chai以及让内容更容易阅读。
关于unit-testing - 使用Mocha、Chai和Sinon来测试延迟 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31951503/