QUnit.test()
添加版本:1.0.0.
描述
QUnit.test( name, callback )
使用 QUnit.test()
定义测试。
参数 | 描述 |
---|---|
name (字符串) |
正在测试的单元的标题 |
callback (函数) |
执行测试的函数 |
回调参数
参数 | 描述 |
---|---|
assert (对象) |
一个 断言 对象 |
回调函数的 assert
参数包含所有 QUnit 的 断言方法。使用它来进行测试断言。
QUnit.test()
可以自动处理 Promise 的异步解析,只要您将“then-able” Promise 作为回调函数的结果返回。
另请参阅
变更日志
QUnit 1.16 | 添加了对异步函数和 Promise 返回的支持。 |
示例
示例:标准测试
一个实际示例,使用断言参数。
function square (x) {
return x * x;
}
QUnit.test('square()', assert => {
assert.equal(square(2), 4);
assert.equal(square(3), 9);
});
示例:异步测试
在上面的示例之后,QUnit.test
也支持 JS 异步函数 语法。
QUnit.test('Test with async-await', async assert => {
const a = await fetchSquare(2);
const b = await fetchSquare(3);
assert.equal(a, 4);
assert.equal(b, 9);
assert.equal(await fetchSquare(5), 25);
});
示例:带有 Promise 的测试
在 ES5 和更早的环境中,您也可以从标准测试函数中返回一个 Promise。这也支持其他 then-able 值,例如 jQuery.Deferred
和 Bluebird Promise。
此示例返回一个 Promise,该 Promise 在等待 1 秒后解析。
function fetchSquare (x) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve(x * x);
}, 1000);
});
}
QUnit.test('Test with Promise', function (assert) {
return fetchSquare(3).then(function (result) {
assert.equal(result, 9);
});
});