vue-cli 3.0 集成 jest 单元测试 组件中获取dom宽度代码报错

vue 用 jest 单元测试,组件中用到了某个dom元素的宽度 clientWidth,但是在跑单元测试的时候无法通过 window.querySelect 获取到这个元素,放在 nextTick 中也不行。

clipboard.png

xxx.vue 代码

...
methods {
    resize () {
      let width = document.querySelector('#m-editor').clientWidth;
      let editTools = document.querySelector('.edit-tools');
      if (width > 780) {
        editTools.style.width = '600px';
      } else if (680 < width) {
        editTools.style.width = '480px';
      } else if (640 < width) {
        editTools.style.width = '400px';
      } else if (500 < width) {
        editTools.style.width = '320px';
      } else if (width < 500) {
        editTools.style.width = '0';
      }
    },
    ...
   }

测试代码

import { shallowMount } from '@vue/test-utils'
// import HelloWorld from '@/components/HelloWorld.vue'

// describe('HelloWorld.vue', () => {
//   it('renders props.msg when passed', () => {
//     const msg = 'new message'
//     const wrapper = shallowMount(HelloWorld, {
//       propsData: { msg }
//     })
//     expect(wrapper.text()).toMatch(msg)
//   })
// })
import markdownEditor from '@/components/markdownEditor.vue'

describe('markdownEditor.vue', () => {
  it('renders props.input when passed', () => {
    const msg = '# hello world'
    const wrapper = shallowMount(markdownEditor, {
      propsData: { value: msg }
    })
    wrapper.vm.$nextTick(() => {
      expect(wrapper.html()).toMatch('<h1>hello world</h1>')
    })
  })
})
阅读 3.6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题