NetSquared: Branding As a Non-Profit recap
May 15, 2016
State of payment processing for hybrid mobile apps
January 27, 2019
Show all

Testing vue js single file components with ava

Ken Powers has a great writeup on how to test vue components by using the vue-node library. I will present an alternative way to test vue js single file components with ava without using the vue-node library. The reasons are as follows:

  • Don’t want to introduce webpack as a dependancy or are using an alternate bundler like Brunch.
  • Spinning up a webpack instance whenever running a test makes the test slow.

I found this solution by looking at a pull request in the avoriaz-ava-example that has since been reverted. Originally the example used vue-node and then was replaced with an alternative (and imo superior method). Later on it was reverted back to using vue-node. Credit goes to jackmellis for coming up with this solution. His fork of the avoriaz-ava-example can be found here.

This method uses libraries which intercept nodes module loading that will transpile the vue files before compilation.

In addition to having ava installed, you will need the following two libraries.

npm i -D require-extension-hooks require-extension-hooks-vue

Then we’ll need to specify a helper file for ava to do the .vue module transpiling

And in the helper setup.js (credit to jackmellis)

Now you can test your components:

For testing the html elements one helpful library is avoriaz

A big gotcha is if you’re using a UI library such as onsenui, you won’t be able to mount the vue component in your tests. Since the ava testing environment not a full browser environment. A workaround can be found here but it is hacky with stubbing a lot out.

3 Comments

  1. ira says:

    Hello Michael, very interesting article, thank you. One question
    I get the following error when I am trying to import for testing a Foo.vue component which imports a Bar.js component, which by its turn import another Baz.js component

    For example:

    In Foo.vue
    ==============

    import Bar from ‘./some/path/Bar’

    export default {

    data() {/**/}
    /*more code*/
    }

    {
    /* some testing code */
    } )

    I get the error:

    > @ test /home/igeorgas/webApps/work_projects/apptree2
    > mocha ‘tests/**/*.test.js’ –reporter=nyan –compilers js:babel-core/register –require ./tests/FE/helpers/setup.js

    /home/user/resources/assets/js/core/Bar.js:1
    (function (exports, require, module, __filename, __dirname) { import Baz from “./some/path/Baz”;

Leave a Reply

Your email address will not be published. Required fields are marked *