Unknown custom element: - did you register the component correctly? error on with <nuxt /> component in default.vue Jest

Viewed 1892

I'm trying to write tests for default.vue file which has the following code:

default.vue

<template>
 <div>
   <top-nav :class="isSticky ? 'fixed-top stickyAnimate' : ''" />
   <main>
     <nuxt />
   </main>
   <footer />
 </div>
</template>

<script>
import TopNav from '../components/TopNav.vue';
import Footer from '../components/Footer.vue';
import StickyNavMixin from '../mixins/stickyNavMixin';

export default {
  components: {
    TopNav,
    Footer,
  },
  mixins: [StickyNavMixin],
  data() {
    return {
      loading: true,
    };
  },
  mounted() {
    if (!window.location.hash) {
      this.loading = false;
    }
  },
};
</script>

then my test look like this default.spec.js

import { createLocalVue, shallowMount } from '@vue/test-utils';
import BootstrapVue from 'bootstrap-vue';
import StickyNavMixin from '../mixins/stickyNavMixin';
import Default from '../layouts/default.vue';
import TopNav from '../components/TopNav.vue';
import Footer from '../components/Footer.vue';

const localVue = createLocalVue();
localVue.use(BootstrapVue);
localVue.mixin(StickyNavMixin);

describe('Default', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallowMount(Default, {
      localVue,
    });
  });

  test('is a Vue instance', () => {
    expect(wrapper.isVueInstance()).toBeTruthy();
  });

  test('has navbar component', () => {
    expect(wrapper.find(TopNav).exists()).toBe(true);
  });
});

When I ran this test, I get error says: [Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.found in --->

Please guide me to a right direction. Thank you in advance!

1 Answers

I figured out how to get past that error. I had to just stub it out of the wrapper. You don't have to import Nuxt, just string 'nuxt' will replace it as a stubbed element in the wrapper:

describe('DefaultLayout', () => {
  let wrapper;

  afterEach(() => {
    wrapper.destroy();
  });

  /** mount **/
  test('is a Vue instance', () => {
    wrapper = mount(DefaultLayout, {
      localVue,
      stubs: ['nuxt'],
    });
    expect(wrapper.isVueInstance()).toBeTruthy();
  });

 /** shallowMount **/
 test('is a Vue instance', () => {
    wrapper = shallowMount(DefaultLayout, {
       localVue,
       stubs: ['nuxt', 'top-nav', 'footer'],
    });
    expect(wrapper.isVueInstance()).toBeTruthy();
    // expect(wrapper.html()).toBe('<div>'); => this is to debug see below for output
  });
});

//DEBUG
"<div><top-nav-stub class=\"\"></top-nav-stub> <main><nuxt-stub></nuxt-stub> . 
</main> <footer-stub></footer-stub></div>"
Related