如何在TestCafe脚本中添加递归函数来检查XHR响应?

6

我正在尝试编写一个测试下载功能的代码,其中需要检查XHR响应是否有“ READY”状态。 我在TestCafe中创建了一个客户端函数,并使用了Promises,但在递归的情况下失败了。

我该如何修复代码以处理这种情况?

P.S. 对于新手问题,请多多包涵,我刚开始自动化测试之旅。


fixture`Download report works`


test
    .requestHooks(logger)//connected a request hook, will wait for logger request 
    ('I should be able to download PDF report from header of the page', async t => {
        //recursively check if response status is READY, and then go to assertions

        const waitForDownloadResponseStatus = ClientFunction((log) => {
            return new Promise((resolve,rejects)=>{
                const waitForStatus=()=>{

                        const arrayFromResponse = JSON.parse(log.response.body);
                        const responseStatus = arrayFromResponse.status;
                        if (responseStatus == 'READY')
                        {
                            resolve(responseStatus);
                        } 
                        else {
                            waitForStatus();
                        }
                    }
                waitForStatus();
                })
        });
        //page objects
        const reportTableRaw = Selector('div.contentcontainer').find('a').withText('April 2019').nth(0);
        const downloadPdfButton = Selector('a.sr-button.sr-methodbutton.btn-export').withText('PDF');
        //actions.

        await t
                .navigateTo(url)
                .useRole(admin)       
                .click(reportTableRaw)//went to customise your report layout
                .click(downloadPdfButton)
                .expect(logger.contains(record => record.response.statusCode === 200))
                .ok();//checked if there is something in logger
        const logResponse = logger.requests[0];

                // const arrayFromResponse = JSON.parse(logResponse.response.body);
                // const responseStatus = arrayFromResponse.status;

        console.log(logger.requests);
        await waitForDownloadResponseStatus(logResponse).then((resp)=>{
            console.log(resp);
            t.expect(resp).eql('READY');
        });     


    });
1个回答

5
当您将对象作为参数或依赖项传递给客户端函数时,它将接收传递的对象的副本。因此,它无法检测到外部代码所做的任何更改。在这种特定情况下,waitForStatus函数将无法达到其终止条件,因为它无法检测到外部请求挂钩所做的log对象的更改。这意味着该函数将无限期运行,直到消耗所有可用的堆栈内存。之后,它将以堆栈溢出错误失败。
为了避免这种情况,如果更改contains函数的谓词参数,则可以检查响应是否具有状态READY。请看下面的代码:
.expect(logger.contains(record => record.response.statusCode === 200 &&
                                  JSON.parse(record.response.body).status === 'READY'))
.ok({ timeout: 5000 });

另外,您可以使用timeout选项。这是一种断言可以花费的时间(以毫秒为单位),在测试失败之前通过。


1
现在我明白了。你建议的代码可行!不需要编写冗长的函数。谢谢你的回答,安德烈! - Yulia
1
我们很高兴听到这段代码对您有所帮助。我可以请您将我们的答案标记为“解决方案”,以便其他用户更容易发现吗? - Vladimir A.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接