javascript - 在测试中使用回调排序
问题描述
我正在做一个需要令牌才能运行的测试。需要将此标记传递给比较函数。但我不了解如何等待令牌才能继续执行测试。我是新的JS,所以很抱歉。这是我的测试代码:
describe('Offline Comparison', function () {
token = getToken('appName');
console.log('Token' + token);
files.forEach(function (file) {
it('Comparando file ' + file, function (done) {
this.timeout(15000);
const id = file.split('./screenshots/')[1];
compare(file, id, token, function (response) {
console.log(JSON.stringify(response, null, 4));
expect(response.TestPassed).to.be.true;
done();
});
});
});
});
function getToken(applicationName, callback) {
request.post('http://localhost:8081/token',
{
json: {
application_name: applicationName
}
},
(error, response, body) => {
console.log('Token: ' + body.Token);
return callback(body.Token)
});
}
解决方案
您的getToken()
函数是异步的并且需要回调。您不能只是调用它并期望并回答,您需要向它传递一个回调函数,它将以令牌作为参数进行回调。你需要这样的东西来获取令牌:
describe('Offline Comparison', function () {
getToken('appName', function(token){ // <- pass getToken a callback
console.log('Token' + token); // <- token should now be available
files.forEach(function (file) {
it('Comparando file ' + file, function (done) {
this.timeout(15000);
const id = file.split('./screenshots/')[1];
compare(file, id, token, function (response) {
console.log(JSON.stringify(response, null, 4));
expect(response.TestPassed).to.be.true;
done();
});
});
});
});
});
推荐阅读
- linux - 检查作为 shell 脚本输入提供的可变数量的位置参数的有效性
- python - ConnectionResetError: [WinError 10054] 现有连接被远程主机强行关闭。解决这个问题?
- python - 将 .py/.pyw 转换为 .exe
- javascript - 无法在 ReactBootstrap 的选项卡中使用表单
- regex - 匹配多行字符串中的字符串,同时排除特殊字符
- solr - 如何使用 Kerberized 集群禁用 Infra Solr 和 Spark2 上的身份验证
- php - Return 语句在 php 中不起作用,尽管该值存在,但返回时仍然变量给出 null
- visual-studio-code - VSCode 关闭编辑器历史记录
- django - Django simplejwt JWTAuthentication 权限
- azure - Azure服务总线队列触发函数MessageReceiver错误,操作被取消