Getting [Vue warn]: Unknown custom element: <b-modal> even though bootstrap-vue is registered

3.3k Views Asked by At

A BootstrapVue b-modal component in a custom Vue component loads correctly in the browser. However, when testing using mocha+mochapack, it generates a Vue warning that the b-modal element is not registered. The test is using a localVue object that has BootstrapVue registered. All other bootstrap custom elements seem to be loading correctly, and do not generate any warnings.

I tried various things, including importing BModal from 'bootstrap-vue' and registering it as a component directly, but still got the same error.

import {mount, createLocalVue} from "@vue/test-utils"
import MyCustomModal from '../js/MyCustomModal';

const localVue = createLocalVue();

import BootstrapVue from 'bootstrap-vue'
localVue.use(BootstrapVue);

describe('MyCustomModal', () => {
    let wrapper = mount(MyCustomModal,{
            localVue
        });

    it('the content is "this is the content"', () => {
        expect(wrapper.find(".modal-content").text()).toEqual('this is the content');
    });


});

The custom Vue component:

<template>
    <b-modal>
        <div class="modal-content">this is the content</div>
        <b-form>
           my form
        </b-form>
    </b-modal>
</template>

<script>
    export default {
        data(){
            return {};
        }
    }
</script>

The tests run correctly and pass, but it outputs the Vue warning for the b-modal element. It doesn't output the warning for b-form.

3

There are 3 best solutions below

8
Robson Braga On

If only shallowMount not work. You can try stub your bootstrap's components individually.

Like this:

import {shallowMount} from "@vue/test-utils";
import { BModal, BForm } from 'bootstrap-vue';
import MyCustomModal from '../js/MyCustomModal';

describe('MyCustomModal', () => {
    let wrapper = shallowMount(MyCustomModal,{
            stubs: {
                "b-modal": BModal,
              "b-form": BForm
            }
        });

    it('the content is "this is the content"', () => {
        expect(wrapper.find(".modal-content").text()).toEqual('this is the content');
    });

});
2
Troy Morehouse On

You need to set the attachToDocument: true flag when you mount b-modal (or your test component/app). It needs reference to the document/body in order for it to open (needs to add classes, etc to <body> as well as a few listeners.

0
Rodolfo Santos On
import Vue from 'vue';
import {mount} from "@vue/test-utils"
import MyCustomModal from '../js/MyCustomModal';
    
import BootstrapVue from 'bootstrap-vue'
Vue.use(BootstrapVue);

describe('MyCustomModal', () => {
    let wrapper = mount(MyCustomModal);

    it('the content is "this is the content"', () => {
        expect(wrapper.find(".modal-content").text()).toEqual('this is the content');
    });


});

Try that.