How do I mock this Vue injection?

Viewed 4037

I have a Vue 3 component that, when mounted in tests, cause warnings:

console.warn node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:40
  [Vue warn]: injection "Symbol(VueToastification)" not found.
    at <ModifyJob ref="VTU_COMPONENT" >
    at <VTUROOT>

I assume it's this one complaining https://github.com/Maronato/vue-toastification/blob/master/composition/index.js#L30.

I have nearly 100 of these warnings, so it's kind of hard to read test-run output. I've tried to mock provide for this dependency, but I can't seem to succeed:

let provide = {}
provide[VueToastification] = VueToastification
provide['VueToastification'] = VueToastification
provide[Symbol(VueToastification)] = VueToastification
provide[Symbol('VueToastification')] = VueToastification
provide['Symbol(VueToastification)'] = VueToastification

let options = {
    global: {
        provide: provide,
    }
}
mount(ModifyJob, options)

Is this some Vue2/Vue3 incompatibility or do I just not understand the docs at https://vue-test-utils.vuejs.org/v2/api/#global-provide ? Can someone help me get rid of these warnings, ideally by allowing me to inject a mock so I can test that toasts are made?

2 Answers

That error actually indicates that the plugin isn't installed in the test Vue instance. You could make VueToastification available to the component under test through the global.plugins mounting option:

import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
import VueToastificationPlugin from 'vue-toastification'

it('initializes', () => {
  shallowMount(MyComponent, {
    global: {
      plugins: [VueToastificationPlugin]
    }
  })
})

Alternatively, if you want to verify that toast() (from VueToastification's useToast()) is called, you could mock vue-toastification:

import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
jest.mock('vue-toastification')

it('should call toast', () => {
  const toast = jest.fn()
  require('vue-toastification').useToast.mockReturnValueOnce(toast)
  shallowMount(MyComponent).vm.showToast()
  expect(toast).toHaveBeenCalled()
})

I solved setting a global list of plugins according to https://next.vue-test-utils.vuejs.org/api/#config-global:

// In a jest.setup.js file
import { config } from "@vue/test-utils";
import VueToastificationPlugin from "vue-toastification";

config.global.plugins = [VueToastificationPlugin];

// In your jest.config.js
module.exports = {
  ...
  setupFilesAfterEnv: ["./jest.setup.js"],
};

Related