unit-testing - 使用Mocha、Chai和Sinon来测试延迟 Action

标签 unit-testing mocha.js chai

我想为异步进程创建单元测试。我创建了一个简单的情况模拟,使用超时来延迟警报。 (真正的过程是动态加载 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/

相关文章:

python - 覆盖 python 日志记录以提高测试效率

unit-testing - 测试 RXJS 自定义管道

android - 如何将 TestNG 集成到 Android 项目中?

mocha.js - 如何订阅 mocha 套件事件?

node.js - 轮询 URL 直到在 JSON 响应中设置特定值 : Mocha, 集成测试

c - 如何编写单元测试以确保 C 中科学计算中的数值准确性?

javascript - 异步运行 mocha js (AND-like)

javascript - 在 Chai 中,expect().to.be.true 是如何工作的?

node.js - chai-http 结束后写入

javascript - 使用 Puppeteer、Mocha 和 Chai 断言 html 标签属性中存在文本