【发布时间】:2018-10-07 00:07:23
【问题描述】:
我正在尝试创建一个函数来测试异步代码,但我有点迷茫,我希望下面的 TEST_F 和 TEST 函数也适用于异步代码,例如加载图像。
const CHECK = (actual, expected) => {
return (actual === expected);
};
const TEST = (name, ...testFunctions) => {
console.log(name+':');
for (let test of testFunctions)
console.log(test);
};
const TEST_F = (name, f) => {
const tStart = performance.now();
const check = f();
const tEnd = performance.now();
const duration = tEnd - tStart;
const details = name + ': ' + '(' + duration + ') = ' + check;
return details;
};
const imageDownload = (path, successCallback) => {
let img = new Image();
img.addEventListener("load", successCallback, false);
img.src = path;
return img;
};
TEST("TestImage",
TEST_F("testImageDownload", () => {
let spyCountSuccess = 0;
const expectedCountSuccess = spyCountSuccess + 1;
const successCallback = () => {
spyCountSuccess++;
};
const pathImage = 'https://i.imgur.com/Wutekcp.jpg';
imageDownload(pathImage, successCallback);
const actualCountSuccess = spyCountSuccess;
return CHECK(actualCountSuccess, expectedCountSuccess);
})
);
使用上面的代码,即使加载了图像,我也总是会出错,因为我没有正确处理异步的概念,我想了解如何调整代码从而也测试 ascincrono 代码。
【问题讨论】:
-
您是否考虑过使用现有的测试框架来处理 mocha 等异步代码?
-
@Paul 我只是在学习。我喜欢创造我的工具,我学习更多这样的东西。我想在我创建的测试工具中添加异步代码测试,以了解有关测试的更多信息。 github.com/perdugames/cacau
标签: javascript unit-testing asynchronous testing