vue test utils get offsetWidth is 0

Viewed 641

I tried to get the value of offsetwidth but it was always 0

Template.spec.js

import { mount } from '@vue/test-utils';
import Template from '~/components/Template.vue';
describe('Template', () => {
  const wrapper = mount(Template);
  it('get offsetWidth', async () => {
    await wrapper.vm.$nextTick()
    console.log(wrapper.element.offsetWidth)  // 0
  });
});

Template.vue

<template>
  <div class="template" style="width:100px">
  </div>
</template>
2 Answers

Take a look at your CSS. if the class of .template contains any of the following rules, the result you are receiving is expected. Elements that will not be displayed, may not be included in the flow.

your-stylesheet.css

display: none;
overflow: hidden;
float: left;
height: 0;   /* will be 0 without any content in the element */
position: absolute;

** There may be others, but any of those may cause the issue. Just make sure that there is content and that it is displayed prior to trying to measure it.

Good Luck!

You can mock the CSS styles as well as offsetWidth in your test files but it can only be done after the tag is rendered.

element.style.width = '100px'
Object.defineProperties(element, {
  offsetWidth: { value: 100 },
  clientWidth: { value: 100 },
})
Related