【发布时间】:2019-07-29 17:20:10
【问题描述】:
我有一个问题。 我制作函数 test() 和 assert();
我测试我的代码。 但结果和我的不一样。
当我在函数 test() 中使用异步等待时。 结果是
should support flattening of nested arrays : fail
should support filtering of arrays : fail
support notEqual : ok
adds 1 + 2 to equal 3 : ok
但我删除了函数 test() 中的异步等待。 结果是
support notEqual : ok
adds 1 + 2 to equal 3 : ok
should support flattening of nested arrays : fail
should support filtering of arrays : fail
为什么?
const _ = require("lodash");
const sum = (a, b) => {
return a + b;
};
const isEven = n => {
return n % 2 == 0;
};
const appendLazy = (arr, data, time) => {
return new Promise(resolve => {
setTimeout(() => {
arr.push(data);
resolve(arr);
}, time);
});
};
async function test(msg, callback) {
try {
await callback();
console.log(`${msg} : ok`);
} catch (e) {
console.log(`${msg} : fail`);
}
}
const assert = {
equal: (targetA, targetB) => {
if (targetA !== targetB) throw Error;
},
notEqual: (targetA, targetB) => {
if (targetA === targetB) throw Error;
}
};
test("support notEqual", () => {
assert.notEqual(undefined, null); //pass
});
test("adds 1 + 2 to equal 3", () => {
assert.equal(1 + 2, 3); //pass
});
test("should support flattening of nested arrays", function() {
assert.detailEqual([1, 2, 3, 4], [1, 2, 3, 5]); //fail
});
test("should support filtering of arrays", function() {
const arr = [1, 2, 3, 4, 5, 6];
assert.detailEqual(_.filter(arr, isEven), [2, 4, 5, 6]); //fail
});
我必须在我的测试函数中使用异步等待。 为什么原因不同???
【问题讨论】:
-
什么是
assert.detailEqual? -
那是因为 console.log 不等待回调完成
标签: javascript async-await try-catch