【问题标题】:How do I mock this Vue injection?我如何模拟这个 Vue 注入?
【发布时间】:2021-02-19 13:28:19
【问题描述】:

我有一个 Vue 3 组件,在测试中安装时会导致警告:

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>

我猜是这个人在抱怨https://github.com/Maronato/vue-toastification/blob/master/composition/index.js#L30

我有近 100 条此类警告,因此很难阅读测试运行输出。我试图模拟提供这种依赖关系,但我似乎无法成功:

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)

这是一些 Vue2/Vue3 不兼容还是我只是不理解 https://vue-test-utils.vuejs.org/v2/api/#global-provide 的文档?有人可以帮我摆脱这些警告吗,最好是允许我注入一个模拟,这样我就可以测试吐司的制作了吗?

【问题讨论】:

    标签: vue.js vuejs3 vue-test-utils


    【解决方案1】:

    该错误实际上表明该插件未安装在测试 Vue 实例中。您可以通过global.plugins 安装选项使VueToastification 可用于被测组件:

    import { shallowMount } from '@vue/test-utils'
    import MyComponent from '@/components/MyComponent.vue'
    import VueToastificationPlugin from 'vue-toastification'
    
    it('initializes', () => {
      shallowMount(MyComponent, {
        global: {
          plugins: [VueToastificationPlugin]
        }
      })
    })
    

    或者,如果你想验证toast()(来自VueToastificationuseToast())是否被调用,你可以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()
    })
    

    【讨论】:

      【解决方案2】:

      我解决了根据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"],
      };
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多