Search code examples
vue.jsjestjsvue-routervue-test-utilsvue-i18n

Vue Unit test - child components & i18n


I am entering the world of application testing and I have some doubts about how to test, mainly because of the languages ​​and child components.

Basically, the first tests I'm trying to run is to cover whether the listing pages have the right data.

The structure I have at the moment is the following structure -

components structure

baseTable
  |- columnHeader
  |- rowRoute

Depending on the route the user is on, in the baseTable component the table body is dynamically imported.

Example, the active page is users, so it will import rowUsers.

The first error that occurs to me, is that in the columnHeader component it presents the error

vm.$t is not a function

the second error is in the component rowUsers in which it says

[Vue warn]: Unknown custom element: <router-link> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

the third error is that the rowUsers component does not exist.

expect( wrapper.find( rowUsers ).exists()).toBe( true ); Expected: true Received: false

I tried to pass the i18n and the router-link on the wrapper, but it still didn't work.

import { shallowMount } from '@vue/test-utils';
import baseTable from '@/components/bundles/tables/baseTable';
import rowUsers from '@/components/dynamic/tables/rowUsers';
import i18n from '@/plugins/i18n';

describe( 'Lists', () => {

    it( 'Users list', () => {
        // mock from user
        const fields = [{
            email: '[email protected]',
            name: 'user 1',
            role: 'admin'
        }];

        const wrapper = shallowMount( baseTable, {
            propsData: {
                url: 'users',
                headers: [ null, 'name', 'email', 'role' ],
                fields: fields,
                row: 'Users'
            },
            stubs: ['router-link'],
            i18n
        });

        expect( wrapper.find( rowUsers ).exists()).toBe( true );
    })

})

Any suggestion?


Solution

  • You can mock $t like this:

    shallowMount( baseTable, {
      mocks: {
        $t: (msg) => msg
      }
    })
    

    or you can add a global mock to avoid repeated code in every test file:

    import VueTestUtils from "@vue/test-utils"
    
    VueTestUtils.config.mocks["$t"] = msg => msg
    

    https://lmiller1990.github.io/vue-testing-handbook/mocking-global-objects.html#example-with-vue-i18n