VueJS Default props factory function and test coverage

1.3k Views Asked by At

Facing a really, really, really annoying issue here.

Consider a sample Vue component here:

<template>
   <div>
    Some arbitrary html elements here
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    myObjectProp: {
      type: Object,
      default: () => {},
    },
    myArrayProp: {
      type: Array,
      default: () => [],
    },
  },
}
</script>

When I run my unit tests, using vue-test-utils, and show coverage, the coverage report shows the lines where I use a factory function to return the default prop value, as required in the Vue spec, are not covered.

This of course, brings down the test coverage which affects my ability to push code. Particularly for smaller components, this anonymous factory function will represent 50% of the funcs coverage!

What I've tried:

Defining a helper function:

function resolveProp(args) {
 return args;
}

And using as such:

<script>
export default {
  name: 'MyComponent',
  components: {},
  props: {
    myObjectProp: {
      type: Object,
      default: resolveProp({}),
    },
    myArrayProp: {
      type: Array,
      default: resolveProp([]),
    },
  },
}

</script>

But then, the resolveProp function is not covered. I don't want to have to write this function and accompanying unit test for every component file.

So, I thought I could try installing the helper function as a mixin or a Vue plugin with the relevant unit test. But of course, I need to reference it via this and this is not available when I need to resolve the prop!

Any ideas how I can either suppress this issue or tell my test runner to ignore it altogether?

The test command I run is vue-cli-service test:unit which I believe just runs jest.

Is there something I can put in my jest.config.js to ignore this?

Thanks in advance

1

There are 1 best solutions below

1
On

I was trying to find an answer for a simular issue I was having with my test coverage, I couldn't get 100% of tests covered coz the default function should be tested. Couldn't find anything on SO.

After some tryings I got to a solution on how to test the default. Not sure if would help you, but solved my case:

expect(wrapper.vm.$options.props.myObjectProp.default.call()).toEqual([])

expect(wrapper.vm.$options.props.myArrayProp.default.call()).toEqual([])