Why is createLocalVue needed when testing Vue components with Vuex?

Viewed 1805

I'm reading through the Vue Testing Cookbook and Vue Test Utils's docs, where they touch on testing components with Vuex. Both sources advise using createLocalVue, but I don't fully understand why. We already have a couple of tests that use Vuex but don't use createLocalVue, and they work. So why do these sources suggest using createLocalVue?

Here's the test that appears to be a bad practice according to those sources. Is this code going to break something down the road? Is it causing unwanted side-effects we're not aware of?

import { mount } from '@vue/test-utils';
import Vuex from 'vuex';
import Component from 'somewhere';

// We don't use this and yet the code seems to work
// const localVue = createLocalVue()
// localVue.use(Vuex)

describe('Foo Component', () => {
    let wrapper;

    beforeEach(() => {
        wrapper = mount(Component, {
            // localVue, <-- We don't use this
            store: new Vuex.Store({
                modules: {
                    app: {
                        namespaced: true,
                        // ... more store stuff
                    }
                }
            }) 
        })
    });

    it('should contain foo', () => {
        expect(wrapper.contains('.foo')).toBe(true);
    });
});
1 Answers

From docs:

localVue: A local copy of Vue created by createLocalVue to use when mounting the component. Installing plugins on this copy of Vue prevents polluting the original Vue copy.

In your tests, you might want to make particular changes and install plugins on the tested Vue instance. Using localVue ensures those changes are reset for every test.

An obvious advantage is you don't have to install all plugins for all tests. So your tests will be faster.

Also, when your tests get a bit more complex, if you don't use localVue you'll experience tests failing erratically based on their order, because the previously ran test, even though it passed, modified the Vue instance in a way that breaks your next test. But the next test passes when ran in isolation.
The type of errors which typically imply hair loss.

Using localVue provides a type of certainty most developers welcome when running tests. If you feel adventurous, don't use it.

It's a recommendation, not an imposition.

Related