测试方法返回错误“最终`assert.async`解析后断言”

时间:2015-03-11 16:29:05

标签: unit-testing qunit sinon

我正在尝试测试javascript方法,如下所示,

var spyPostRender = sinon.spy(proxy, "postRender");
var done = assert.async();
proxy.init();
done();
assert.ok(spyPostRender.calledOnce, "postRender() function was called.");

其中init()在内部调用ajax服务,但是当我这样做时,我得到了以下错误。有人可以帮我解决这个问题吗?

  

最终assert.async解析后的断言@ 85 ms来源:at   Object.QUnit.assert.Assert.ok   (http://code.jquery.com/qunit/qunit-1.17.1.js:1296:8

仅供参考 - 我使用的是QUnit-1.17.1

提前致谢

2 个答案:

答案 0 :(得分:1)

在您致电done()后,您正在立即呼叫init()功能,这是不正确的。您应该只调用异步活动已完成的done()方法(因此单词“done”)。完成此操作的简单方法是向init()方法添加回调函数:

proxy.init = function(callback) {
  // just using jQuery as an example, could be any framework...
  $.ajax({
    url: "/some/api/service",
    // ...
    complete: function() {
      callback(/* maybe pass some data back? */);
    }
  });
};

然后你可以在测试它时传递一个匿名函数:

QUnit.test("Test the init method", function(assert) {
  var spyPostRender = sinon.spy(proxy, "postRender");
  var done = assert.async();
  proxy.init(function() {
    assert.ok(spyPostRender.calledOnce, "postRender() function was called.");
    // Notice that we only call done() once everything async is complete!
    done();
  });
});

答案 1 :(得分:0)

第一个解决方案由@jakarella发布,替代解决方案没有修改现有代码正在使用sinon.stub

或者也许使用sinon.stub覆盖proxy.postRender来执行异步断言:

var done = assert.async();

var _postRender = proxy.postRender;
var stubPostRender = sinon.stub(proxy, "postRender", function() {
  var result = _postRender.apply(this, arguments);

    // Do your real assertions BEFORE invoking the final (i.e. you may have multiple) `done` callback
  assert.ok(stubPostRender.calledOnce, "postRender() function was called.");

  // The final `done` callback MUST be called AFTER all real assertions have been made
  done();

  return result;
});

proxy.init();

以上代码是从github解决方案中复制的 https://github.com/jquery/qunit/issues/777