首页 > 解决方案 > 使用夹具下载 XML

问题描述

我想将一个 XML 文件从服务器保存到本地以供以后检查。因为 TestCafe 不允许开箱即用下载文件,所以我做了一些研究并发现:

import fs from 'fs';

const downloadLocation = './downloads/saved.xml'; //downloadlocation on macOS
const fileDLUrlBase = 'https://example.com/downloads/xml/mytest'; //dynamic generated xml

fixture('download test fixture');
test('download test', async t => {
  await t.navigateTo(fileDLUrlBase);
  await t.wait(30000);
  // Wait 30 seconds
  await t.expect(fs.fileExistsSync(downloadLocation));
});

我在这里阅读了很多关于堆栈溢出的评论和帖子,但我真的很困惑。ALL,真的 ALL 解决方案,标记为 s 解决方案,在这里不起作用。

作为示例: 断言文件下载的 Testcafe 示例

我克隆了这个夹具,但 TestCafe 会崩溃。但是这个问题被标记为已解决。在我看来,下载文件的任何解决方案都不起作用,这让我很困惑。

有人可以帮帮我吗?

标签: testingdownloadautomated-testse2e-testingtestcafe

解决方案


我检查了一个简单的场景,它在我这边没有任何错误。

服务器.js

var express = require('express');
var fs      = require('fs');
var app     = express();

app.get('/', function (req, res) {
    res.send('<html>\n' +
         '<head>\n' +
         '</head>\n' +
         '<body>\n' +
         '<a href="/download/">Download file</a>\n' +
         '</body>\n' +
         '</html>');
});

app.get('/download/', (req, res) => {
    var files = fs.createReadStream("text-document.txt");
    res.writeHead(200, {'Content-disposition': 'attachment; filename=text-document.txt'});
    files.pipe(res)
})

app.listen(3000, function () {
    console.log('http://localhost:3000/');
});

测试.js

import { Selector } from 'testcafe';
import fs from 'fs';

fixture `fixture`;

test
    .page('http://localhost:3000/')
    ('download', async t => {
        await t.click(Selector('body > a'));

        await t.wait(1000);

        await t.expect(fs.existsSync('path-to-file\\text-document.txt')).ok();

});

命令:

testcafe chrome test.js

结果:

 fixture
 √ download


 1 passed (2s)

您能否澄清您的系统环境详细信息?如果你能提供像上面这样的自己的简单项目,那就太好了。它将帮助我们重现问题。


推荐阅读