首页 > 解决方案 > 如何在 testcafe 脚本中添加递归函数检查 xhr 响应?

问题描述

我正在尝试编写一个测试下载作品,它需要检查 xhr 响应是否有状态 READY。我使用 Promise 在 TestCafe 中创建了一个客户端函数,但在递归的情况下它会失败。

我应该如何修复我的代码来处理这种情况?

PS对新手的问题表示歉意,我刚刚开始了我的自动化测试之旅。


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');
        });     


    });

标签: javascriptautomated-testse2e-testingweb-testingtestcafe

解决方案


当您将对象作为参数或依赖项传递给客户端函数时,它将接收传递对象的副本。因此它将无法检测到外部代码所做的任何更改。在这种特殊情况下,waitForStatus函数不会达到其终止条件,因为它无法检测到log外部请求挂钩对对象所做的更改。这意味着这个函数将无限期地运行,直到它耗尽所有可用的堆栈内存。之后,它将因堆栈溢出错误而失败。

READY为避免这种情况,您可以在更改函数的谓词参数时检查响应是否具有状态contains。看看下面的代码:

.expect(logger.contains(record => record.response.statusCode === 200 &&
                                  JSON.parse(record.response.body).status === 'READY'))
.ok({ timeout: 5000 });

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


推荐阅读