Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch Vue.js warnings for unit testing required properties

We are porting a very large project into Vue.js and would like to thoroughly implement our unit testing suite as we go.

We would like to validate that components are having all their required properties set at creation, my test case looks something like:

describe('Input', () => {
  it('fail initialization with no value', () => {
    const vm = mount(Input, {
      propsData: {},
    });

    // expecting above to fail due to required prop 'value'
  });
});

The component Input is expected to contain a property value. I can see via the console warning emitted that it is missing but we would like to catch this in our unit tests. Directly testing this doesn't make much sense but once we have components nesting several components, making sure that each component correctly initialises its sub components is important and this is achieved by assuring ourselves that the above test should fail and be caught failing.

There is no exception raised however, we have had ideas to hook into the Vue.warnHandler but this just seems like a lot of work for simply confirming that a constructor works as expected.

Is there a recommended approach to doing this with Vue.js?

like image 546
fungus1487 Avatar asked Nov 07 '22 05:11

fungus1487


1 Answers

Unfortunately it looks like the only way to do this is to hook into the Vue.warnHandler

I used a variable and reset it on the afterEach hook (Mocha) like so:

let localVue;
let hasWarning = false;
function functionToWrapShallowMount(propsData) {
    const Wrapper = shallowMount(Control, {
        propsData,
        provide: {
            $validator: () => {}
        },
        localVue
    });
    return Wrapper;
}
before(() => {
    localVue = createLocalVue();
    Vue.config.warnHandler = () => {
        hasWarning = true;
    };
});
afterEach(() => {
    hasWarning = false;
});

it('throws a warning', () => {
    const { vm } = functionToWrapShallowMount({
        name: 'foooo',
        value: 'bad'
    });
    vm.name.should.eq('foooo');
    hasWarning.should.eq(true);
});

The catch to this is you cannot use the localVue from Vue test utils you must use the Vue instance imported from vue.

like image 141
Zach Leighton Avatar answered Nov 13 '22 01:11

Zach Leighton