Search code examples
browserifyvuejs2vue-componentkarma-mochavueify

Running Karma tests with VueJS single file component using Vueify


I am trying to run my unit tests with Karma. I have calendar.tests.js file that looks a lot like this:

import { handleSelectDay } from '../components/Calendar/index.vue'
describe('Calendar', () => {
  describe('handleSelectDay', () => {
    const data = {};

    describe('updates data', () => {
      it('should set the selectedDay to a new id', () => {
        handleSelectDay('id');
        expect(data.daySelected).to.equal('id');
      });
    });
  });
});

When I run this test with Karma I get the following: TypeError: (0 , _index.handleSelectDay) is not a function is not a function

My karma.conf.js looks like:

module.exports = function (config) {
  config.set({

    frameworks: ['browserify', 'mocha'],
    files: ['static/js/apps/FutureHours/test/calender.tests.js'],
    preprocessors: {
      'static/js/apps/**/test/*.js': ['browserify']
    },
    browsers: ['Chrome'],
    logLevel: 'LOG_DEBUG',

    plugins: [
      'karma-mocha',
      'karma-browserify',
      'karma-chrome-launcher',
      'karma-spec-reporter'
    ],

    browserify: {
      debug: true,
      transform: [['babelify', { presets: ['env'] }], 'vueify']
    }
  })
}

How can I get Karma to play nice with VueJS single file components?


Solution

  • The problem with this is you can't have a named export from a .vue component. Instead, any methods used in the component will have to accessed via the component object in a unit test. Any functions used outside the component's methods, should probably live in their own ES module to make unit testing them much easier.