5 mins to fix jest tests for app with: Unknown custom element: — did you register the component correctly?

Raymond
2 min readMar 27, 2021

--

Are you getting the following error?

error

Solutions

1. Are you missing packages?

  1. Check your node_modules package and install missing packages / components modules. Or reinstall your node_modules via `npm install`.

Reference:

2. Are you stubbing your jest tests correctly?

If you are writing unit tests and want to test the functionality of a component individually, then setup the shallowMount function and test it. Stub inside of jest unit tests.

Difference between shallowMount and mount

mount:

The mount method takes the Vue component as a first argument and returns its vue instance along with some helper which is used to interact with a component instance like set props, trigger clicks, etc.

shallowMount:

The shallowMount method also works similar to the mount method the main difference is shallowMount doesn’t render child components so that it allows us to test the component in isolation to make sure that child components are not included in the test.

If you want to test a nested component, then use the mount function.

I’d recommend using shallowMount function, as it’s for unit testing a component.

In my case, I had to stub my font-awesome icons from @nuxtjs/fontawesome-module

import { shallowMount } from '@vue/test-utils'
import Index from '@/pages/index.vue'
import { fas } from '@fortawesome/free-solid-svg-icons'
describe('index.vue', () => {
test('is a Vue instance', () => {
const wrapper = shallowMount(Index, {
stubs: ['fa'], // <<<<<STUB HERE>>>>>
components: {},
computed: {
faPhone() {
return fas.faPhone
}
}
})
expect(wrapper).toBeTruthy()
})
})

3. Are you ignoring node_modules correctly?

In most cases you are required the following line inside your jest.config.js you just have to ignore the component module when you are running your tests. Otherwise it would run the tests inside your node_modules as well.

//jest.config.js
transformIgnorePatterns: [
'/node_modules/'
'/node_modules/(?!<SOME PACKAGE HERE>)',
],

To Sum Up

  • Install missing packages or reinstall node_modules
  • mount/shallowMount and stub your components when required or when you are using external modules.
  • Ignore node_modules from your jest.config.js

Cheers! Hope you found this article helpful! 🍻

tags: #solution #nuxtjs #vuejs #javascript #typescript #development

--

--