Testing 在失败之前,您是否尝试过多次断言?
我对API执行PUT请求,然后执行GET请求,以查看我所放置的内容是否存在。问题在于,API在PUT和GET请求之间可能需要一段时间才能让GET请求看到要传播的数据。我使用的测试框架只是添加了等待,但我知道这是不可取的,并且我已经看到了测试的缓慢或失败。为了尝试删除等待,我添加了以下内容,但我想知道是否有更干净的方法来实现这一点Testing 在失败之前,您是否尝试过多次断言?,testing,automated-tests,chai,e2e-testing,testcafe,Testing,Automated Tests,Chai,E2e Testing,Testcafe,我对API执行PUT请求,然后执行GET请求,以查看我所放置的内容是否存在。问题在于,API在PUT和GET请求之间可能需要一段时间才能让GET请求看到要传播的数据。我使用的测试框架只是添加了等待,但我知道这是不可取的,并且我已经看到了测试的缓慢或失败。为了尝试删除等待,我添加了以下内容,但我想知道是否有更干净的方法来实现这一点 // A function that simply tries x times for the checkingFunction to return a truthy
// A function that simply tries x times for the checkingFunction to return a truthy value.
async function waitForCorrectApiResponse(checkingFunction, maxTries = 5, waitPeriod = 3000) {
let tries = 0;
while(maxTries > tries) {
const apiResponse = await checkingFunction();
if(apiResponse) {
return apiResponse;
}
// A wait method
await t.wait(waitPeriod);
tries ++;
}
}
const response = waitForCorrectApiResponse(async function(){
const apiResponse = await getApiResponse() // some random get API response function
if (apiResponse.body.hasOwnProperty('whatever') {
return apiResponse;
}
}
// Then do Chai assertions against response.....
例如,在我的脑海中,我希望能够做如下的事情…基本上,对一个值尝试一组Chai断言x次,如果每次为false,则重置该值
async function waitForCorrectApiResponse(checkingFunction, maxTries = 5, waitPeriod = 3000) {
let tries = 0;
while(maxTries > tries) {
const apiResponse = await checkingFunction();
if(apiResponse) {
return apiResponse;
}
// A wait method
await t.wait(waitPeriod);
tries ++;
}
}
const response = waitForCorrectApiResponse(async function(){
const apiResponse = await getApiResponse() // some random get API response function
Chai.expect(apiResponse).to.have.property('whatever');
// Rest of Chai assertions.....
}
更新:
因此,我已经能够做到以下几点,我认为这是一个更好的,但想知道是否有更好的东西
async函数retryChai(apiCall,断言,maxTries=5,waitPeriod=3000){
设t=0;
while(最大尝试>尝试){
尝试++;
const apiResponse=等待apiCall();
试一试{
const ok=等待断言(apiResponse);
返回ok;
}
捕获(e){
如果(最大尝试次数===尝试次数){
断言(apiResponse)
}
}
等待t.等待(waitPeriod);
}
}
雷特里猜(
异步函数(){
//返回API响应
},
功能(响应){
//把柴的断言放在这里,即。。。。
expect(response.body.documents).to.be.empty;
}
)
据我所知,您正在使用TestCafe框架。TestCafe有一个内置的机制。因此,不需要使用柴图书馆
总的来说,您的方法看起来不错。很难说清楚如何改进代码,因为您只共享了一小段代码,而不是一个工作示例。
在我看来,您的第一种方法更实用,因为您将API请求和断言拆分为不同的函数