4
votes

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 !

1
The <location> component's code is probably more relevant here. - ceejayoz
I do not want to know from where the error comes... I just want to know if there is a way to know if error occurs during .$mount() because the unit test is not failing. - Jorelia
The location component is a complex component, not really relevant here... and the cause of the failing is related to $ (JQuery) as it is not part of the build of the component. Making an import solved the problem.... What I'm looking for, is a way to trap such kind of error...during the .$mount() to make my test failing instead of to be passed. - Jorelia

1 Answers

1
votes

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.