Vue 2 Jest - [Vue warn]: Cannot find element: #app

21 Views Asked by At

I am new to Jest trying to run my first test. I am getting cannot find element #app. I have mounted my app in main.js file with the id 'app'. I am using localVue to mount in the spec file. But while compiling it triggers to main js and tries to find the id 'app'. Below is my spec file

// Libraries
import Vuetify from 'vuetify'
import Vuex from 'vuex';
import Vue from 'vue';

// Components
import home from '@/views/pages/home.vue';

// Utilities
import {createLocalVue, mount, shallowMount} from '@vue/test-utils';


describe('home.vue', () => {
    let vuetify, localVue;
    let store;
    beforeEach(() => {
        const div = document.createElement('div');
        div.setAttribute('id', 'app');
        document.body.appendChild(div);

        localVue = createLocalVue();
        localVue.use(Vuex);
        vuetify = new Vuetify()
        store = new Vuex.Store({
            state: {},
            actions: {},
            mutations: {},
        });
    })
    afterEach(() => {
        const div = document.getElementById('app');
        if (div) {
            document.body.removeChild(div);
        }
    });
    it('check submit button is disabled if fields are empty', async () => {
        const wrapper = mount(home, {
            attachTo: document.getElementById('app'),
            localVue,
            vuetify,
            store,
            stubs: ['router-link', 'router-view'],
        })
        const name = '';

        wrapper.find('.dname').setData(name);
        await Vue.nextTick();

        expect(wrapper.vm.decoderName).toBe(name);

        expect(wrapper.vm.isValidForm).toBeFalsy();
        expect(wrapper.find('.createBtn').element.disabled).toBe(true);
    });
});

enter image description here

1

There are 1 best solutions below

0
Haritha Perumal On

I fix it by adding a setup file. Add a setup file in jest.conf.js:

setupFiles: ['<rootDir>/test/unit/setup']

Create setup.js and create the div.

createAppDiv();
function createAppDiv() {
  var app = document.createElement('div');
  app.setAttribute('id', 'app');
  document.body.appendChild(app);
}

Now Run the test, the error will disappear.