gpt4 book ai didi

javascript - Jasmine + 异步函数

转载 作者:行者123 更新时间:2023-12-03 02:08:40 26 4
gpt4 key购买 nike

这是我的代码:

'use strict';

var unitID = 0;

var getById = function(generalOptions, specificOptions) {


describe('API tests for: ' + specificOptions.name, function() {
var url = generalOptions.baseUrl + specificOptions.route;



// GET all items
it('= = = GET ALL test for ' + specificOptions.name + ' return status
code 200', function(done) {
generalOptions.request.get({
url: url
}, function(error, response, body) {
expect(response.statusCode).toBe(200);
expect(JSON.parse(body)).not.toBeFalsy();

if (specificOptions.route == '/devices/') {
var bodyJS = JSON.parse(body);
unitID = bodyJS.devices[0].id;
} else {
unitID = '';
}
console.log('Result 1 - ' + unitID);
done();

});
});


//GET by ID
it('= = = GET by ID test for ' + specificOptions.name + ' return status code 200', function(done) {
console.log('Result 2 - ' + unitID);
generalOptions.request.get({
url: url + unitID
}, function(error, response, body) {
expect(response.statusCode).toBe(200);
expect(JSON.parse(body)).not.toBeFalsy();
done();
});
});
})
};

module.exports = getById;

我需要等待,而 unitID 将使用第一个 GET 请求进行更新,然后在下一个请求中使用。

问题是,它是异步工​​作的,第二个请求中的 unitID 保持为 0。

可以展示如何使用 async/await 或 Promises 实现解决方案吗?谢谢!

出于调试原因,我执行 console.log。现在它打印:
结果 2 - 0
结果 1 - 59dffdgfdgfg45545g

最佳答案

您不应该以一种测试的输出进入另一个测试的方式编写测试。每个“它”应该是独立的。

相反,您应该进行两次调用(嵌套调用)来实现 unitID 的值,或者理想情况下,您应该模拟服务以返回“it”期望的数据。

关于javascript - Jasmine + 异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49678303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com