如何在开玩笑地进行测试时解决警告:无法安装组件:模板或渲染函数未定义

时间:2019-07-10 11:20:46

标签: typescript vue.js webpack jestjs ts-jest

我看到过很多关于相同错误的帖子,但是我只在用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>

Navbar.vue

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

Navbar.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");
  });
});

测试本身通过。我假设我丢失/设置了某些错误的配置,但不确定到底是什么。我也在使用Typescript。

最佳配置:

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"
  }
};

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

1 个答案:

答案 0 :(得分:0)

我通过将moduleFileExtensions中扩展名的顺序修改为以下内容来解决警告:

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

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