SoFunction
Updated on 2025-04-05

Implementation of vue-cli3 karma unit test

Karma

Karma is a testing tool that allows your code to be tested in a browser environment. The code may be designed to be executed on the browser side. In the node environment, some bugs may not be exposed (such as style testing). If your code will only run on the node side, then you do not need to use karma.

vue-cli3 combined with karma

After searching, I foundvue-cli-plugin-unit-karmaPlugin, integrates vue-cli3 and karma, but the result is not so perfect, and an error is still reported during execution.

But hard work pays off, I finally found a solution, the steps are as follows

Installation dependencies

npm install --save-dev @vue/test-utils karma karma-chrome-launcher karma-mocha karma-sourcemap-loader karma-spec-reporter karma-webpack mocha

Created in the layer (note that it is conf, not config!!!)

The content is as follows

var webpackConfig = require('@vue/cli-service/')
 = function (config) {
  ({
    frameworks: ['mocha'],
    files: [
      'tests/**/*.' //In the tests directory, all the test files at the end of the tests directory
     ],
     preprocessors: {
       '**/*.': ['webpack', 'sourcemap']
    },
    webpack: webpackConfig,
    reporters: ['spec'],
    browsers: ['ChromeHeadless']
  })
}

Add script commands

"test": "karma start"

Finally, just execute npm run test

refer to

Testing Single-File Components with Karma

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.