我正在为vuejs组件编写单元测试用例。
当我尝试使用shallowMount
来vue-test-util
组件时,我遇到了错误:
TypeError:$不是VueComponent.mount上的函数 (src / components / gridComponent / index.vue:7579:7)
我的代码:
import $ from 'jquery';
global['$'] = global['jQuery'] = $;
import { shallowMount, createLocalVue } from '@vue/test-utils'
import gridComponent from '@/components/gridComponent/index'
describe('grid view component', () => {
it('has the expected html structure', async () => {
let wrapper = await shallowMount(gridComponent, {
stubs: ['GridLayout', 'GridItem'],
propsData : {componentsList}
})
expect(wrapper.element).toMatchSnapshot()
})
})
下面是gridComponent的代码:
import * as $ from 'jquery'
export default {
name: 'gridComponent',
components: { GridLayout, GridItem, DxpCommonModal },
props: ['componentsList'],
watch: {
componentsList: function (newVal, oldVal) {
// eslint-disable-next-line
this.matchingComponents = this.componentsList
}
},
data () {
return {
isDraggable: true,
isResizable: true
}
},
created () {
},
computed: {
...mapGetters(['getResources'])
},
mounted () {
$('#headerComponent').html(this.getSelectorHTML(this.siteDetails.header))
$('#footerComponent').html(this.getSelectorHTML(this.siteDetails.footer))
this.addHtmlOfComponentsInAPage()
},
destroyed () {
},
methods: {
addHtmlOfComponentsInAPage () {
this.selectedPage.Components.forEach((element, index) => {
$('#${index}').html(this.getSelectorHTML(this.selectedPage.Components[index]))
})
},
getSelectorHTML (component) {
const element = document.createElement(component.componentType)
element.setAttribute('content-id', new Date().getTime().toString())
if (!this.values && component.demoData) {
this.values = component.demoData
}
if (this.values) {
this.createMarkup(element, this.values)
this.values = ''
}
return element
}
}
}
答案 0 :(得分:0)
在组件中,尝试
const $ = require('jquery')
将其放在导致错误的方法中。
这将让您知道您是在某个地方取消定义还是重新定义它。
您可能需要jsdom。
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html>`);
const $ = require('jquery')(window);