同步:
有时候如果我们想判断方法执行的次数,可以通过间接设置expect(n);//可以将expect的参数放到test的第二参数来简化;
QUnit.test("expect test", function(assert) { expect(2); //assert run two times; function calc(x, operation) { return operation(x); } var result = calc(2, function(x) { assert.ok(true,"calc() calls operation function"); //use ok to check; return x*x; }); assert.equal(result,4,"2 square equal 4"); });
同理,除了方法执行次数外,还可以判断事件发生次数;
QUnit.test("a test", function(assert) { expect(1); //when click the body will fail; var $body = $("body"); $body.on("click",function() { assert.ok(true,"body was clicked!"); }); $body.trigger("click"); });
异步:
在异步上,需要使用asyncTest替代test;同时使用start方法标记,当异步方法返回之后继续执行的地方;
同理,使用expect判断异步方法或事件是否执行;
QUnit.asyncTest("asyncChronous test;one second later!", function(assert) { expect(1); setTimeout(function() { assert.ok(true,"Passed and ready to resume!"); QUnit.start(); //set start to tell QUnit to continue when callback end; },1000); })
注意:如果在测试同步的时候,需要测试通过其它方法促发事件的情况下;此时如果与异步一起测试,那么在等待异步方法返回的时间内,会给同步的方法测试带来副作用而无法判断出同步是否执行。