Search code examples
automated-testse2e-testingvue-clitestcafedotenv

Getting TestCafe to recognize dotenv variables


I might be mixing up concepts, but 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), I found I could make a file in .env.test for test values like so:

VUE_APP_MY_COOL_VARIABLE

which I would then access in my test code like so:

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

}

However, I get the following error:

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

Seems like my environment variables aren't getting picked up. I build my code like so: vue-cli-service build --mode test.


Solution

  • Here's how I solved my issue. When debugging, I did a console.log of process.env and noticed that the variable that vue recognizes wasn't visible during testcafe's run. From our package.json:

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

    Also this bit of javascript is run by both the test and mainline code, so I had to use a conditional.

    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' });
    }