如何解决开玩笑的错误:TypeError:$不是函数

时间:2019-05-07 12:47:45

标签: unit-testing vue.js jestjs vue-test-utils

我正在为vuejs组件编写单元测试用例。

当我尝试使用shallowMountvue-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
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题排查

在组件中,尝试

const $ = require('jquery')

将其放在导致错误的方法中。

这将让您知道您是在某个地方取消定义还是重新定义它。

解决方案2

您可能需要jsdom。

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html>`);
const $ = require('jquery')(window);