让 TestCafe 识别 dotenv 变量

Getting TestCafe to recognize dotenv variables

我可能混淆了概念,但是 I'd read that it's possible to get TestCafe to recognize variables of the form process.env.MY_COOL_VARIABLE. Also for my Vue.js frontend (built using Vue-CLI, which uses dotenv under the hood),我发现我可以在 .env.test 中为测试值创建一个文件,如下所示:

VUE_APP_MY_COOL_VARIABLE

然后我会像这样在我的测试代码中访问它:

test('my fixture', async (t) => {
 ...
 await t
      .click(mySelector.find('.div').withText(process.env.VUE_APP_MY_COOL_VARIABLE));
 ...

}

但是,我收到以下错误:

"text" argument is expected to be a string or a regular expression, but it was undefined.

我的环境变量似乎没有被提取。我这样构建我的代码:vue-cli-service build --mode test.

你试过process.env[VUE_APP_MY_COOL_VARIABLE]了吗?值得注意的是,dotenv 中的所有内容都以字符串形式返回,因此您可能需要自己进行转换。例如:

function getEnvVariableValue(envVariable: string) {
    // Cast to boolean
    if (envVariableValue.toUpperCase() === "TRUE") {
        return true;
    } else if (envVariableValue.toUpperCase() === "FALSE") {
        return false;
        // Cast to number
    } else if (!isNaN(Number(envVariableValue))) {
        return Number(envVariableValue);
    } else {
        return envVariableValue;
    }
}

您也可以尝试在根文件夹中创建一个 .env 文件,看看它是否以这种方式选择它。我通过将 dotenv 作为依赖项包含在 package.json 中直接在我的项目中使用它,它以这种方式工作。

TestCafe 不提供对开箱即用的 .env 文件的支持。您可以创建一个需要 dotenv 模块的测试文件并加载您的配置文件:

// enable-dotenv.test.js
require('dotenv').config({ path: '.my.env' });
testcafe chrome enable-dotenv.test.js tests/

这是我解决问题的方法。调试时,我做了 process.envconsole.log 并注意到 vue 识别的变量在 testcafe 的 运行 期间不可见。来自我们的 package.json:

"test:ui:run": "VUE_APP_MY_COOL_VARIABLE=ui-test yarn build:test && testcafe -a ../ui-test-server.sh chrome",

此外,javascript 的这一点在测试和主线代码中都是 运行,所以我不得不使用条件。

import * as dotenv from 'dotenv';

if (process.env.npm_package_scripts_test_ui_run) { // are we running a testcafe script
  dotenv.config({ path: '.env.test' });
}