Should I test Vue.js private functions?

Viewed 2598

So after I read common tips and watched the video about testing provided by Vue.js I decided to test only behaviors of my components. But I maybe misunderstand the concept. Here is the component:

<template>
        <es-btn
          class="a"
          round
          outline
          color="primary"
          @click="skipScan"
        >
          Skip Upload
        </es-btn>
</template>
<script>
export default {
  data: () => ({
    uploadScanningDialog: false,
  }),

  methods: {
// public functions here which will be tested

    skipScan() {
      hideDialog();
      triggerSkipScan();
    },
  },
}

// private functions here as vue.js suggests

function hideDialog() {
  this.uploadScanningDialog = false;
}

....

</script>

I want to test the behavior:

it('should hide itself and show next dialog when Scan Button is clicked', () => {
    const data = {
      uploadScanningDialog: true,
    };
    wrapper.setData(data);

    expect(wrapper.vm.uploadScanningDialog).toBeTruthy();
    wrapper.find('.a').trigger('click');
    expect(wrapper.vm.uploadScanningDialog).toBeFalsy();
  });

So here are the questions and errors:

  1. Should I do test this way, by triggering the action instead of calling the method itself? Because I used to test by calling the method and expecting some results, not triggering the component who calls the method

  2. Shouldn't I test the private functions? Because my test tries to call real method, so the test I share gets error. I will mock them but I'm not sure how to continue

1 Answers

Generally it is better to unit test your code through its public api, where possible.

This improves maintainability, as:

  • It allows you to refactor any private functions, without having to update your unit tests.
  • If you make changes to your private functions, you can then assert that you haven't broken anything by running your unit tests against your public api.

Whether you run your unit tests by calling a public method or triggering a DOM event is a matter of choice.

The latter gives greater test coverage as you are also testing if you have wired up the event to the event handler function correctly in your template; but it is slightly less maintainable, as if you change your template you may have to update your tests.

Related