Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock this Vue injection?

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?

like image 745
Bittrance Avatar asked Oct 14 '25 20:10

Bittrance


1 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()
})
like image 142
tony19 Avatar answered Oct 17 '25 10:10

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!