Skip to content

[Docs] Test usage of provide  #713

@anbraten

Description

@anbraten

It took me quite some time to get an example of how to test a provide of a component. I want to test if the component uses the provide function correctly and if it does some stuff with the injected data from possible child components. Which is somehow the opposite of the existing option which is already in-build to vue-test-utils:

mount(ChildComponent, {
  global: {  
    provide: { 
      title: 'My title'
    }
  }
})

I finally got it working with the following code. Maybe this helps others and can eventually be added to the docs.

I had some interesting errors on my way:

  • adding a name to the childComponent breaks it
  • leaving the h(childComponent) away breaks the slot (inside child: getCurrentInstance().parent is null)

Sample

<template>
  <div class="parent">
    <p class="title">{{ title }}</p>
    <slot />
  </div>
</template>

 <script lang="ts">
import {defineComponent} from 'vue';

export defineComponent({
    setup() {
      const title = ref('Parent');
      provide('title', title);
      return { title };
    },
});
</script>
import { mount } from '@vue/test-utils';
import { h, inject, nextTick, provide, Ref, ref } from 'vue';
import parentComponent from './parentComponent';

describe('Repro', () => {
  it('should update injected title', async () => {
    expect.assertions(1);
    // given

    // the child component works like a mock to simulate missing inject option 
    const childComponent = {
      template: '<div />',

      setup() {
        const title = inject<Ref<string>>('title');
        if (title) {
          title.value = 'Child';
        }
        return {};
      },
    };

    // when
    const wrapper = mount(parentComponent, {
      slots: {
        default: h(childComponent),
      },
    });
    await nextTick();

    // then
    expect(wrapper.find('.title').text()).toStrictEqual(`Child`);
  });
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions