Search code examples
vue.jsvue-clivue-cli-3

Get vue-cli-service test:unit to load environment variables from a different file (not .env.test)


Using Vue CLI and Jest. In my packages.config I have:

"test:unit": "vue-cli-service test:unit",

From trial and error, I have found that this causes the .env.test environment variable file to load, and sets the NODE_ENV variable to production. This is the the basic test I am testing with:

import { mount } from '@vue/test-utils'
import Home from './Home'

describe('Home', () => {
  test('is a Vue instance', () => {
    console.log('=================================================');
    console.log('ENVVAR=' + process.env.ENVVAR);
    console.log('NODE_ENV=' + process.env.NODE_ENV);
    console.log('=================================================');
    const wrapper = mount(Home);
    expect(wrapper.isVueInstance()).toBeTruthy();
  });
});

Unfortunately vue-cli-service doesn't have a --mode option when using test:unit. I need to get vue-cli-service to load variables for a specific environment, and also to set NODE_ENV to something specific, for example:

"test:unit": "vue-cli-service test:unit --mode foo",

If that existed, I need it to load .env.foo environment variables. Ideally it would change NODE_ENV to foo as well, but that is less concerning.

If I change my packages.config to be:

"test:unit": "set NODE_ENV=foo&&vue-cli-service test:unit",

It does set NODE_ENV to foo, but vue-cli-service insists on loading .env.test instead of .env.foo. Furthermore, I get a bunch of errors like this:

  console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
    [Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

    found in

    ---> <App>
           <Root>

So is there any way possible to get vue-cli-service to load specific environment variables, and not .env.test?

Thanks


Solution

  • To resolve this, I ended up not even using vue-cli-service.

    In my packages.json under scripts:

    "test:unit": "./node_modules/.bin/jest",
    

    Then I created this setup.js file:

    process.env.NODE_ENV='foo';
    var dotenv = require("dotenv");
    // Load in reverse order (variables in second file will not override variables in first)
    dotenv.config({ path: '.env.foo' });
    dotenv.config({ path: '.env' });
    

    And referenced it in my jest.config.js:

    setupFiles: ["./src/.jest/setup.js"],
    

    Proper environment variables now load, and NODE_ENV is set to 'foo' (in this example).