Menu

Poland

GRANDMETRIC Sp. z o.o.
ul. Metalowa 5, 60-118 Poznań, Poland
NIP 7792433527
+48 61 271 04 43
info@grandmetric.com

Sweden

Drottninggatan 86
111 36 Stockholm
+46 762 041 514
info@grandmetric.com

UK

Grandmetric LTD
Office 584b
182-184 High Street North
London
E6 2JA
+44 20 3321 5276
info@grandmetric.com

US Region

Grandmetric LLC
Lewes DE 19958
16192 Coastal Hwy USA
EIN: 98-1615498
+1 302 691 94 10
info@grandmetric.com

  • en
  • pl
  • se
  • VueJS unit testing config with examples

    VueJS unit testing config with examples

    Date: 13.07.2020



    Unit testing is a great way to ensure that the application meets business requirements. They also help you write a new functionality with confidence that you won’t break existing features. In this article, I will walk you through VueJS unit testing configuration. Then, I’ll show you a working example of how you can write tests for your own components.

    If you already have a project created with Vue CLI you can skip installation steps and run: vue add @vue/unit-jest

    Installation

    npm install -g @vue/cli
    vue create testing-example

    Push the enter button to pick the default config.

    Then generate a new VueJS project with a basic development setup with unit testing capabilities.
    cd testing-example
    npm install @vue/cli-plugin-unit-jest @vue/test-utils

    Configuration

    Append test:unit command to the end of scripts section in package.json:

    "scripts": {
      ...
      "test:unit": "vue-cli-service test:unit"
    },

    Create jest.config.js file and add the following lines:

    module.exports = {
      preset: '@vue/cli-plugin-unit-jest',
      collectCoverage: true
    }
    

    As a result, you’ll be able to run your unit tests and see the code coverage report.

    Writing unit tests

    After the configuration step, add simple functionality to HelloWorld.vue component:

    <template>
      <div>
        <input v-model="name" />
        <button @click="formatMsg">Show message</button>
        <p>{{message}}</p>
      </div>
    </template>
    
    <script>
    export default {
      name: "HelloWorld",
      data() {
        return {
          name: "",
          message: ""
        };
      },
      methods: {
        formatMsg() {
          this.message = `Hello ${this.name}`;
        },
      },
    };
    </script>

    In the src folder create __tests__ directory and add file HelloWorld.test.js inside of it.
    The following code will test the functionality of the HelloWorld VueJS component:

    import { mount } from '@vue/test-utils';
    import HelloWorld from '../components/HelloWorld.vue';
    
    describe('HelloWorld test', () => {
      it('should format message on button click', () => {
        const wrapper = mount(HelloWorld);
        const { vm } = wrapper;
        wrapper.setData({
            name: 'Adam',
        });
        const button = wrapper.find('button');
        button.trigger('click');
        expect(vm.message).toBe('Hello Adam');
      });
      /* async keyword is needed because of updating the DOM.
      We need to wait for button click to complete and call formatMsg function.
      Otherwise the last assertion would fail */
      it('should show message on button click', async () => {
        const wrapper = mount(HelloWorld);
        const { vm } = wrapper;
        wrapper.setData({
            name: 'Adam',
        });
        const button = wrapper.find('button');
        await button.trigger('click');
        const p = wrapper.find('p');
        expect(p.text()).toBe('Hello Adam');
      });
    });

    ‘Describe’ block is used to group unit tests together. In ‘it’ block you can name your test and put your assertions (expect function).
    In order to access data of the HelloWorld component, you need to mount it. The vm value unpacked from the wrapper variable will contain properties and methods of the mounted component.
    You can call the npm run test:unit command to check if the tests pass. Additionally, you will get the code coverage report after our tests complete.

    Author

    Adam Skowronek

    Adam Skowronek is currently studying computer science at the Adam Mickiewicz University in Poznań. His interests include web development, software engineering, Linux and backend development.

    Leave a Reply

    Your email address will not be published. Required fields are marked *


    Grandmetric