javascript - 异步测试功能
问题描述
我正在尝试创建一个函数来测试异步代码,但我有点迷茫,我希望下面的 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 代码。
解决方案
经过一些测试,我能够测试异步代码。我不知道我是否会保持这种方式,但它正在工作,我会尝试研究这些行,看看我能改进什么:
const CHECK = (actual, expected) => {
return (actual === expected);
};
const TEST = (name, ...testFunctions) => {
console.log(name+':');
for (let test of testFunctions)
if(test === undefined)
continue;
else
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 TEST_F_ASYNC = (name, f) => {
const tStart = performance.now();
f((check) => {
const tEnd = performance.now();
const duration = tEnd - tStart;
const details = name + ': ' + '(' + duration + ') = ' + check;
console.log(details);
});
};
const imageDownload = (path, successCallback) => {
let img = new Image();
img.addEventListener("load", successCallback, false);
img.src = path;
return img;
};
TEST("TestImage",
TEST_F_ASYNC("testAsync", (done) => {
let spyCountSuccess = 0;
const expectedCountSuccess = spyCountSuccess + 1;
const successCallback = () => {
spyCountSuccess++;
const actualCountSuccess = spyCountSuccess;
const result = CHECK(actualCountSuccess, expectedCountSuccess)
done(result);
};
const pathImage = 'https://i.imgur.com/Wutekcp.jpg';
imageDownload(pathImage, successCallback);
}),
TEST_F('testSync', () => {
return CHECK(1, 1);
})
);
推荐阅读
- javascript - new promise inside a async function in order to grab the value outside of the async function
- javascript - 未检测到 keydown 事件
- android - 如何将应用程序从后台带到前台
- python - 使用 Python 将来自 REST API 的 JSON 数据插入 PostgreSQL 表
- flutter - 如何在 Flutter 中将 Container 上的涟漪效果显示为 IconButton 子项?
- vue.js - vuex 未知动作类型:events/loadAll
- python - 从数据框到桌面中的 Excel
- html - CSS onclick 动画
- core-data - SwiftUI 将 Core Data 实体读入 []
- python - 使用多个字典过滤数据框列