6

I have a problem running the npm run test. The error is

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

SidebarCMS.spect.js

import { shallowMount } from "@vue/test-utils";
import SidebarCMS from "../layouts/SidebarCMS";

const factory = () => {
  return shallowMount(SidebarCMS, {});
};

describe("SidebarCMS", () => {

  test("renders properly", () => {
    const wrapper = factory();
    expect(wrapper.html()).toMatchSnapshot();
  });
});

Can anyone help me?

2 Answers 2

5

You can stub the child components while creating instance. For more information about stubbing components, check out this link.

Try like this, This will resolve your warning!.

const factory = () => {
  return shallowMount(SidebarCMS, {
     stubs: {
      'nuxt-link': true,
      'any-other-child': true
     }
   });
};
Sign up to request clarification or add additional context in comments.

1 Comment

Omg, finally something that works. I have been looking everywhere!
0

The accepted answer from Naren works, but does not account for all use cases.

Use case 1:
I don't need to access inner elements of the NuxtLink. => Stubbing is a good option, so this leads to the answert from Naren:

const wrapper = shallowMount(SidebarCMS, {
  props,
  global: {
    stubs: {
      'nuxt-link': true,
    },
  },
});

Use case 2:
I want to access inner elements of the NuxtLink for some reasons. => Stubbing won't work, instead we can define a custom component in the test file:

Note: We still need to list NuxtLink in the stubs and set it to false:

wrapper = shallowMount(SidebarCMS, {
  props,
  global: {
    stubs: {
      'nuxt-link': false,
    },
    components: {
      'nuxt-link': {
        template: '<a><slot/></a>',
      },
    },
  },
});

What this does is replacing the nuxt-link with the template you define for it. Used html elements inside are kept, the attributes (like classes or the "to" attribute) are automatically applied.

This means, given the following usage of nuxt-link

<nuxt-link
  to="www.example.com"
  class="item-class"
><div>ItemContent</div></nuxt-link>

, the output of wrapper.html will then be

<a to="www.example.com" class="item-class"><div>ItemContent</div></a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.