Jorelia
Jorelia

Reputation: 39

vue.js Unit Test - Error in mounted hook

I'm using Jasmine as unit test framework, and I would like to know how could I know if a vue is correctly mounted. Is there a function, an API from VueJS, a receipt to know the state of the view ?

Actually..the unit test is passing but at the console (terminal or under the browser) I got the the following error : ERROR LOG: '[Vue warn]: Error in mounted hook: (found in xxxx ) - ReferenceError: $ is not defined'

Then I would like that my unit test has a failure on this kind of error instead of passing......?

Here is a quick snapshot of the code:

describe("location component tests suite", () => {

    const getComponent = (data) => {
        let vm = new Vue({
            template : "<div>"
                + "<location"
                + " :data='data'"
                + " label='pick'"
                + " placeholder='placeholder'"
                + " required>"
                + "</location></div>",

            data: {
                data
            }
        });

        return vm;
    };

    it("Validate mount", () => {
        const data= { 'data' : { 'value' : 'VUE'} };
        const vm = getComponent(data).$mount();
        expect(vm.$el.querySelector('div.location-wrapper').getAttribute('class')).toBe('location-wrapper');
        expect(vm.$el.querySelector('input').getAttribute('name')).toBe('pick');
    });
});

Thank you !

Upvotes: 4

Views: 3590

Answers (1)

choasia
choasia

Reputation: 10852

You may want to use Vue.config.errorHandler API which is introduced since v2.2.0.

  1. You can declare a variable as an error-thrown flag (i.e. errorThrown).

     let errorThrown = false;
    
  2. Define the errorHandler function so that errorThrown will be switched to true when it's triggered.

     Vue.config.errorHandler = function (err, vm, info) {
       console.log(info);
       if(info.includes('mounted')) {
         errorThrown = true;
       }
     };
    
  3. Check errorThrown by using expect API in jasmine.

     expect(errorThrown).toBe(false);  // Test will fail here
    

Check the working demo here.
In this way, errors occurred in mounted method will be catched and force unit test to fail.

Upvotes: 1

Related Questions