Vue 单元测试:提供未找到的注入变量

Jit*_*Aji 3 javascript unit-testing vue.js

我有一个包含注入的 vue 文件,它也有一个单元测试文件。当我运行 test: utils 时,我收到以下警告。在测试文件中安装组件时使用提供的正确方法是什么?我尝试按照 vue 测试文档中所示的方式进行操作,但仍然有些问题。

export default {
  name: "Navbar",
  inject: ["emitter"],
  props: {
  ishome: {
      default: true,
      type: Boolean,
    },
  },
  data() {
    return {
      isFeedback: false,
    };
  },

  mounted() {
    this.emitter.on("openFeedback", () => {
      this.isFeedback = true;
    });
    this.emitter.on("closeFeedback", () => {
      this.isFeedback = false;
    });
  },
}
Run Code Online (Sandbox Code Playgroud)
import { mount } from "@vue/test-utils";
import Navbar from "../components/Navbar.vue";
import mitt from "mitt";

describe("Mounted App isHome true", () => {
  try {
    const emit = mitt();
    const wrapper = mount(Navbar, {
      provide: {
        emitter() {
          return emit;
        },
      },
      props: {
        isHome: true,
      },
    });
  } catch (error) {
    expect(error).toBe("");
  }
Run Code Online (Sandbox Code Playgroud)
console.warn node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6533
      [Vue warn]: injection "emitter" not found. 
        at <Navbar isHome=true ref="VTU_COMPONENT" > 
        at <VTUROOT>
    console.warn node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6533
      [Vue warn]: Unhandled error during execution of mounted hook 
        at <Navbar isHome=true ref="VTU_COMPONENT" > 
        at <VTUROOT>
    console.warn node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6533
      [Vue warn]: injection "emitter" not found. 
        at <Navbar isHome=false ref="VTU_COMPONENT" > 
        at <VTUROOT>
Run Code Online (Sandbox Code Playgroud)

sjo*_*nie 6

使用 Vue 3 options API 似乎您需要全局指定提供选项。不过,我在文档中找不到此后,您似乎需要将服务作为属性而不是方法提供。在任何在线文档中都找不到...

const wrapper = mount(Navbar, {
      global: {
        provide: {
          "emitter": emit;
        },
        props: {
          isHome: true,
        },
      });
Run Code Online (Sandbox Code Playgroud)