Angular 6-使用量角器测试文件下载时,如何设置文件目标位置的相对路径

时间:2018-08-09 19:27:59

标签: angular protractor

我需要下载CSV并在量角器测试中检查其内容。这些测试是我们部署过程的一部分,因此此下载的路径必须相对。

再看看其他solutions,我在/ e2e创建了一个名为download的文件夹,并将其添加到我的protractor.conf.js

capabilities: {
      browserName: 'chrome',
      chromeOptions: {
          args: ['--disable-gpu']
      },
      prefs: {
        'download': {
          'prompt_for_download': false,
          'default_directory': '/e2e/download'
        }
      }
    },

这是原始测试,它是单击按钮以下载文件,然后检查我本地的Downloads文件夹中的内容(一旦下载本身实际可用,则需要更改此内容)。

  it('should export the csv', () => {
    const filename = '../../../Downloads/new_Name_List_members.csv';
    const exportButton = testUI.findElementBy({findBy: 'buttonText', value: 'Export to CSV'});
    exportButton.click().then(() => {
      browser.driver.wait(function() {
        // Wait until the file has been downloaded.
        return fs.existsSync(filename);
      }, 5000).then(function() {
        expect(fs.readFileSync(filename, { encoding: 'utf8' })).toContain('username,email,name');
      });
    });
  });

即使我已在capabilities.prefs中指定了路径,但单击该按钮后,文件仍将下载到本地“下载”文件夹中。即使我将其设置为完整路径--- 'default_directory': '/Users/kkanya/Documents/Code/project/e2e/download'-,它仍会下载到本地下载中。

我已经浏览了量角器config.ts file,但找不到能使我更改默认下载目录的任何内容。实际上,我没有看到prefs,这使我相信这可能不是最新的量角器的正确方法。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

这是我想出的。它似乎正在工作。它首先删除download中的e2e目录,然后在下载文件时重新创建它。

请注意,prefschromeOptions的值(我在最初的问题中有此错误。)

protractor.conf.js

exports.config = {
    capabilities: {
      browserName: 'chrome',
      chromeOptions: {
        args: ['--disable-gpu'],
        prefs: {
          download: {
            'prompt_for_download': false,
            'default_directory': './e2e/download'
          }
        }
      }
    },

    ...

    onPrepare() {
      // delete ./e2e/download before tests are run
        rmDir('./e2e/download');
    }

// https://sqa.stackexchange.com/questions/24667/how-to-clear-a-directory-before-running-protractor-tests/27653
var fs = require('fs');  

function rmDir (dirPath) {
  try { var files = fs.readdirSync(dirPath); }
  catch(e) { return; }
  if (files.length > 0)
    for (var i = 0; i < files.length; i++) {
      var filePath = dirPath + '/' + files[i];
      if (fs.statSync(filePath).isFile())
        fs.unlinkSync(filePath);
      else
        rmDir(filePath);
    }
  fs.rmdirSync(dirPath);
};

.spec.ts文件:

  it('should export the csv', () => {
    const filename = './e2e/download/new_Name_List_members.csv';

    const exportButton = testUI.findElementBy({findBy: 'buttonText', value: 'Export to CSV'});
    exportButton.click().then(() => {
      browser.driver.wait(function() {
        // Wait until the file has been downloaded.
        return fs.existsSync(filename);
      }, 5000).then(function() {
        expect(fs.readFileSync(filename, { encoding: 'utf8' })).toContain('username,email,name');
      });
    });
  });

希望这对某人有帮助。