Search code examples
visual-studio-codemocha.jsbabeljsvue-cli-3

What babel or other settings do I need to run Mocha Test Explorer on a vue-cli-3 project?


I've created a vue3 cli project with Mocha testing:

vue create vue_proj_with_mocha_testing 
(accept defaults)
cd vue_proj_with_mocha_testing
vue add unit-mocha

Then in Visual Code I install the Mocha Test Explorer extension, restart, add the folder to the workspace, click the folder, ctrl-shift-p and Mocha Test Explorer : "Enable for a workspace folder". Out of the box Mocha Test Explorer doesn't seem to like vuecli's example.spec.js test:

import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  it('renders props.msg when passed', () => {
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
      propsData: { msg }
    })
    expect(wrapper.text()).to.include(msg)
  })
})

I add this entry to settings.json so that Test Explorer finds the vue "tests" folder, which is different from the default of "test".

"mochaExplorer.files": ["tests/**/*.spec.js"],

And then receive this error in Test Explorer:

import { expect } from 'chai';
^^^^^^

SyntaxError: Cannot use import statement outside a module

This indicates I have some transpiling work to do, and Mocha Test Explorer indicates the way to do that is the "mochaTestExplorer" fields in settings.json, but I'm not sure what combination of babel packages would be required. What should be done to run this out-of-the-box vue-cli-3 test in Mocha Test Explorer in Visual Studio Code? Here is my current guess:

"mochaExplorer.require": [
    "@babel/preset-env",
    "@babel/register", 
    "@babel/polyfill",
    "@babel/plugin-transform-runtime"
],

Solution

  • I'm afraid what you want is not possible - problem is it is not enough to setup Babel correctly. Vue single file components (.vue) need to be processed by Vue Loader which is Webpack loader plugin.

    And there is no easy way how to setup Mocha Test Explorer to use webpack as indicated by the author himself in this thread - Support for vue cli projects

    So I decided to split my tests into two groups, tests/ui (tests using Vue components) and tests/unit (non-ui tests) and use setup described by Fernando with these modifications:

    Configure Mocha Test Explorer to only search for non-ui tests:

    "mochaExplorer.files": "tests/unit/**/*.spec.js",
    

    package.json:

    "test:unit": "vue-cli-service test:unit tests/unit/**/*.spec.js tests/ui/**/*.spec.js",
    

    ...to include both folders when running tests from command-line

    Note: Last step - modifying babel.config.js - is not needed, everything works fine without it....