Search code examples
unit-testingvue.jstestingjestjsvue-test-utils

How to test a Vue component against console errors?


The concept of testing Vue/Js is new to me,so bear with me. Normally if there are errors related to the Vue component I can see them in the browser console.

for example if I have a Vue component:

<template>
    <div>
        {{ number }}
    </div>
</template>

<script>
export default {}
</script>

I will see an error like this: [Vue warn]: Property or method "number" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Now when I want to test a specific component using test tools, how can I check for these kind of errors, I want to make sure that the component is loaded without these errors.

Today I tried using Jset to test this, and I ended up with this:

import { mount } from '@vue/test-utils'
import Component from '../Components/Example.vue'

test('it renders without errors', () => {
    const wrapper = mount(Component)
    expect(wrapper.isVueInstance()).toBe(true);
})

but, that doesn't do it since it will always return true even though 'number' is not defined. How can I check if the component has loaded without console errors.


Solution

  • This is not an error but warning, this is the reason why the component renders.

    A proper testing strategy is to test the behaviour because that the framework doesn't cause warnings doesn't mean that a unit works correctly. A suite with full code coverage won't cause such warnings without a fail.

    console.error calls can be additionally spied to strengthen the test but in this case this is entirely redundant:

    spyOn(console, 'error');
    const wrapper = mount(Component);
    expect(wrapper.find('div').text()).toContain('123456'); // easier to do with a snapshot
    expect(console.error).not.toHaveBeenCalled();
    

    Notice that console and some other built-in methods should be spied and mocked with care because they interfere with testing framework's error reporting.