我正在尝试对Vue组件进行单元测试。我在使用wrapper.find()时遇到错误。
组件如下: snackbar.vue
<script>
import { mapGetters } from "vuex";
export default {
computed: {
...mapGetters({
visibility: "snackbar/visibility",
type: "snackbar/type",
message: "snackbar/message"
})
},
watch: {
visibility(value) {
if (value) {
$("#snackbar").addClass("show " + this.type);
setTimeout(() => {
$("#snackbar").removeClass("show " + this.type);
this.$store.dispatch("snackbar/close");
}, 3000);
}
}
}
};
</script>
<template>
<div id="snackbar">{{ message }}</div>
</template>
在测试中我想使用wrapper.find()获得一个将snackbar作为id的div。
这是spec文件: snackbar.spec.js
import SnackBar from '../../../src/modules/Common/_components/snackbar.vue';
import { mount, createLocalVue } from '@vue/test-utils';
import Vue from 'vue'
import Vuex from 'vuex'
const localVue = createLocalVue()
localVue.use(Vuex)
describe('Snackbar component', () => {
let store
beforeEach(() => {
let state = {
isVisible: false,
message: '',
type: ''
}
let getters = {
'snackbar/visibility': (state) => state.isVisible,
'snackbar/type': (state) => state.type,
'snackbar/message': (state) => state.message
}
store = new Vuex.Store({
modules: {
snackbar: {
state,
getters
}
}
})
})
it('renders the correct markup', () => {
let wrapper = mount(SnackBar, { localVue, store })
let snackbar = wrapper.find('#snackbar');
// some test code related to snackbar
})
})
日志如下:
cross-env BABEL_ENV = test karma start test / unit / karma.conf.js --single-run
30 05 2018 18:18:57.847:INFO [业力]:Karma v1.7.1服务器始于http://0.0.0.0:9876/
30 05 2018 18:18:57.849:INFO [launcher]:启动无限并发的浏览器PhantomJS
30 05 2018 18:18:57.855:INFO [launcher]:启动浏览器PhantomJS
30 05 2018 18:18:58.293:INFO [PhantomJS 2.1.1(Linux 0.0.0)]:连接套接字UwfYAt7yHauyEGfNAAAA,ID为26585183
Snackbar组件
✗呈现正确的标记
undefined不是函数(评估'vNodes.findIndex(function(node){return vNode.elm === node.elm;})')
webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2887:48 <- index.js:145115:83
filter@[native code]
removeDuplicateNodes@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2887:0 <- index.js:145115:23
findVNodesBySelector@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2917:0 <- index.js:145145:30
findVnodes@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2934:0 <- index.js:145162:30
find@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2982:0 <- index.js:145210:27
find$$1@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:3272:0 <- index.js:145500:19
webpack:///test/unit/specs/snackbar.spec.js:38:32 <- index.js:142013:32
PhantomJS 2.1.1(Linux 0.0.0):执行1 of 1(1 FAILED)ERROR(0.622秒/ 0.009秒)
答案 0 :(得分:0)
旧版vue-test-utils存在问题。 IE中不支持findIndex,因此我们从最新版本中删除了findIndex。
如果无法更新到最新的@ vue / test-utils,则可以在运行测试之前添加findIndex polyfill - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex#Polyfill。