Search code examples
javascriptvue.jsjestjsvue-test-utils

How can I DRY up the code by shallowMounting the vue component in the beforeEach hook?


For the first time, I'm implementing a bunch of unit tests in a Vue app using vue-test-utils. The tests do work, however, I'd like to DRY up the code.

At the moment I'm adding the following code to each of my tests:

const wrapper = shallowMount(ConceptForm, {
    localVue,
    router,
    propsData: { conceptProp: editingConcept }
});

Making a test look something like this

it('shows the ctas if the state is equal to editing', () => {
    const wrapper = shallowMount(ConceptForm, {
        localVue,
        router,
        propsData: { conceptProp: editingConcept }
    });

    expect(wrapper.find('#ctas').exists()).toBe(true)
});

I'm doing this because I need to pass this specific propsData to the wrapper. Is there any way that I could shallowMount the component in the beforeEach and then pass the prop?

Thanks!


Solution

  • I think you could achieve what you want using the setProps function of the wrapper object. Consider the following example:

    let wrapper;
    beforeEach(() => {
        wrapper = shallowMount(ConceptForm, {
            localVue,
            router,
            propsData: { conceptProp: editingConcept }
        });
    });
    
    it('shows the ctas if the state is equal to editing', () => {
        wrapper.setProps({ conceptProp: editingConcept });
        expect(wrapper.find('#ctas').exists()).toBe(true)
    });