【问题标题】:Is there a better way to call a .env file exists check function in cypress?有没有更好的方法在 cypress 中调用 .env 文件存在检查功能?
【发布时间】:2021-12-13 06:05:45
【问题描述】:

我想在运行测试之前检查根文件夹中是否存在.env 文件。我在 index.js 中添加了以下函数,但它没有检查文件是否存在。有人可以在这里提出问题吗?

cypress/插件/index.js

const  filePath = "../../../.env";

module.exports = (on, config) => {
  on('file:preprocessor', cucumber()),
      on('before:browser:launch', (browser, launchOptions) => {
        console.log("Print browser name: "+browser.name);
        fileCheck(filePath);  // calling the function here
    
      });
};


function fileCheck(filePath) => {
        try {
            if (fs.existsSync(filePath)) {
                console.log("Awesome ! .env file exists in the root directory ! ");
            }
        } catch(err) {
            console.error(err)
            console.log("Oh !, .env file is missing, please add !");
        }
    }

【问题讨论】:

  • 您是否尝试过将错误处理移至 if/else 块中? fs.existsSync() 返回一个布尔值,因此即使找不到文件,它也会是 false 而不是异常。查看您的代码,我认为如果现在找不到该文件,并且没有引发异常,那么您的代码似乎“什么也不做”。
  • @agoff 将尝试在 else 条件中移动错误条件。让我试试
  • @agoff 我试过了,但这又不行了..

标签: javascript node.js cypress cypress-cucumber-preprocessor


【解决方案1】:

也许在之前的操作中检查它就足够了,然后你可以这样做:

before(() => {
cy.on('fail', (error) => {
  error.message = 'Oh !, .env file is missing, please add !';
  throw error;
})
cy.readFile('.env', {timeout: 50}).should('exist');

});

【讨论】:

  • 谢谢,前面的动作应该在测试文件里面提到吧。但是我需要在cypress/ plugins/ index.js 文件中添加一些东西,因为我想在运行测试文件之前检查一下
  • 这太棒了!我认为没有必要为任务增加额外的复杂性。顺便说一句,cy.once(...) 是另一种将错误捕获限制在cy.readFile() 的选项。阅读后还有cy.off('fail', (error) => {...
猜你喜欢
  • 1970-01-01
  • 2011-06-13
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 2023-01-19
  • 2019-09-01
相关资源
最近更新 更多