首页 > 解决方案 > 记录测试文件下载的 HTTP 请求失败

问题描述

我试图复制这个:

https://devexpress.github.io/testcafe/documentation/test-api/intercepting-http-requests/

我的目标页面有target="_blank"没有办法改变删除这个的属性target

所以测试失败。

示例中的代码的作用不是很清楚。URL 是否必须是存在下载链接的页面?

import { ClientFunction, t, Selector, RequestLogger } from 'testcafe'
import * as fs from 'fs';
import * as path from 'path';
...
const forInvoice = new ForInvoice()
const client = 'STRV s.r.o.'

const url = urlFor('?/timers/unbilledOverview')
const logger = RequestLogger({ url, method: 'post' }, {
logResponseHeaders: true,
logResponseBody:    true
});

fixture.only `For Invoicing`
   .requestHooks(logger);

test('Verify download of .xls and .pdf', async t => {
    await t.useRole(ADMIN_INVOICE)
    await forInvoice.navigateToForInvoicing()
    await forInvoice.filterClient(client)
    await t
        .click(Selector('a').filter('.sc-mini-icon-file.excel-file'))
        .expect(logger.contains(r => r.response.statusCode === 200)).ok();

    const filePath = path.join(__dirname, 'STRV-s-r-o-Attachment');

    console.log(filePath);
    console.log(logger.requests[0].response.headers);

    fs.writeFileSync(filePath, logger.requests[0].response.body);

})

标签: typescriptautomated-testse2e-testingweb-testingtestcafe

解决方案


我注意到在提供的示例中,您没有指定夹具或测试的起始页。这可能是错误的原因。

您提到的 TestCafe 示例执行以下操作:

  1. 创建一个RequestLogger实例,该实例监视对开始测试的同一页面的请求(标​​头和正文)。
  2. 单击按钮以启动文件下载。
  3. 等待服务器的成功响应。
  4. 将响应正文保存到文件中。

过滤器对象中的url参数对应于请求发送到的页面(文档),不必与测试页面的 URL 匹配。

您可以使用带有标准 Web API 的ClientFunction修改页面上的元素。您可以使用以下代码开始:

import { Selector, ClientFunction } from 'testcafe'

const link = Selector('a');

const removeTarget = ClientFunction(() => {
    link().removeAttribute('target');
}, { dependencies: { link } })

fixture`Fixture name`
    .page`https://your_page.com/`;

test('Remove target', async t => {
    await removeTarget();
});

推荐阅读