LoginSignup
7
5

More than 3 years have passed since last update.

Jestテスト実行時「Unknown custom element」が発生した場合の対処法

Last updated at Posted at 2019-12-04

問題の現象

Jestテスト実行時、以下のようなVuetifyコンポーネントのUnknown custom elementの警告が出た場合

$ yarn test
yarn run v1.17.3
$ jest --config jest.config.js
 PASS  test/Button.spec.js
  Button
    ✓ is a Vue instance (18ms)

  console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
    [Vue warn]: Unknown custom element: <v-btn> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

    found in

    ---> <Button>
           <Root>

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.588s
Ran all test suites.
✨  Done in 5.91s.

前提

package.json

package.json
{
  "scripts": {
    "test": "jest --config jest.config.js",
  },
}

コンポーネント

components/Button.vue
<template>
  <v-btn large color="primary" @click="log">
    ボタン
  </v-btn>
</template>

<script>

export default {
  name: 'Button',
  methods: {
    log() {
      console.log('hoge')
    }
  }
}
</script>

テストコード

test/Button.spec.js
import { mount } from '@vue/test-utils'
import Button from '@/components/Button.vue'

describe('Button', () => {
  test('is a Vue instance', () => {
    const wrapper = mount(Button)
    expect(wrapper.isVueInstance()).toBeTruthy()
  })
})

対応内容

  • JestがVuetifyコンポーネントを認識できるように、警告が出たタグのモックを作成する
test/jest.setup.js
import Vue from 'vue'
import VueTestUtils from '@vue/test-utils'

Vue.config.silent = true

// Mock Vuetify components
VueTestUtils.config.stubs['v-btn'] = '<button><slot /></button>'
jest.config.js
module.exports = {
  setupFiles: ['<rootDir>/test/jest.setup.js'],    // Load Mock setting
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^~/(.*)$': '<rootDir>/$1'
  },
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest'
  },
  moduleFileExtensions: ['js', 'json', 'vue']
}

参考サイト

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5