0

我已经看到很多关于相同错误的帖子,但我只是在使用 Jest 运行测试时才得到它:

    console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
      [Vue warn]: Failed to mount component: template or render function not defined.

      found in

      ---> <Navbar>
             <Root>

导航栏.vue

<template>
...
  <div>
    <Image
      v-if="email"
    />
  </div>
</template>
<script>
module.exports = require("./Navbar.ts");
</script>

导航栏.ts

import Vue from "vue";
import Image from "@/components/Image/Image";

export default Vue.extend({
  name: "Navbar",
  components: {
    Image,
  },
  computed: {
    email() {
      return this.$store.getters.email;
    }
  }
});

Navbar.spec.ts 示例测试

import { mount, createLocalVue } from "@vue/test-utils";
import Navbar from "../Navbar";
import Vuex from "vuex";

const localVue = createLocalVue();
localVue.use(Vuex);
let wrapper;
const state = {
  email: "name@gmail.com"
};
const getters = {
  email: state => state.email
};
const store = new Vuex.Store({ state, getters });

describe("Navbar", () => {
  beforeEach(() => {
    wrapper = mount(Navbar, {
      store,
      localVue
    });
  });

  it("returns correct email from the store", () => {
    expect(wrapper.vm.email).toBe("name@gmail.com");
  });
});

测试本身通过。我假设我缺少/设置了错误的一些配置,但不确定到底是什么。我也在使用打字稿。

笑话配置:

module.exports = {
  displayName: "test",
  roots: ["<rootDir>/src"],
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node", "vue"],
  transform: {
    ".*\\.(vue)$": "vue-jest",
    "^.+\\.tsx?$": "ts-jest"
  },
  testURL: "http://localhost/",
  snapshotSerializers: ["<rootDir>/node_modules/jest-serializer-vue"],
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1"
  }
};

我希望测试仍然可以通过而不会出现控制台错误。

4

1 回答 1

2

我通过将扩展的顺序修改moduleFileExtensions为:

moduleFileExtensions: ["js", "jsx", "json", "vue", "ts", "tsx", "node"],

我还需要使用shallowMount而不是mount因为我有Image提交到我不想执行的 Vuex 存储的子组件。

于 2019-07-15T09:58:00.597 回答