source

bootstrap-vue를 사용한 재스트 실행

itover 2022. 12. 31. 16:37
반응형

bootstrap-vue를 사용한 재스트 실행

요즘 부제랑 부트스트랩 부제랑 일하고 있어요유닛 테스트를 프로젝트에 추가하기로 결정.

저는 유닛 테스트에 익숙하지 않기 때문에, 어떻게 동작하는지 알기 위해서 가능한 한 노력하고 있습니다.

로그인.specs.js

import { shallowMount, mount } from '@vue/test-utils'
import Login from '@/components/auth/Login.vue'

describe('Login.vue', () => {
  it('is a Vue instance', () => {
   const wrapper = mount(Login, {
    mocks: {
     $t: () => 'Connexion' // i18N
    }
   })
  const h2 = wrapper.find('h2')
  expect(h2.text()).toBe('Connexion')
 })
})

Login.vue

<b-row align-h="center">
 <b-col class="text-center">
  <h2>{{ $t('login.connection') }}</h2>
 </b-col>
</b-row>

시험은 다 괜찮은 것 같아요.하지만 이런 희망들을 얻어서 실제로 고칠 방법을 찾을 수 있었어요

[Vue warn] :알 수 없는 사용자 지정 요소: - 구성 요소를 올바르게 등록했습니까?재귀 구성 요소의 경우 "이름" 옵션을 제공해야 합니다.

[Vue warn] :알 수 없는 사용자 지정 요소: - 구성 요소를 올바르게 등록했습니까?재귀 구성 요소의 경우 "이름" 옵션을 제공해야 합니다.

그래서 주위를 둘러보니 아빠에게 이 아이 컴포넌트를 추가해야 할 것 같아요.

다음은 이들 컴포넌트의 매뉴얼입니다.

구성 파일도 추가합니다(vue-cli 3에서 생성하는 파일과 동일합니다).

jeast.congif 를 클릭합니다.js

module.exports = {
  moduleFileExtensions: [
  'js',
  'jsx',
  'json',
  'vue'
 ],
 transform: {
  '^.+\\.vue$': 'vue-jest',
  '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest- transform-stub',
  '^.+\\.jsx?$': 'babel-jest'
 },
 moduleNameMapper: {
  '^@/(.*)$': '<rootDir>/src/$1'
 },
 snapshotSerializers: [
  'jest-serializer-vue'
 ],
 testPathIgnorePatterns: [ //I've added this one, not sure if usefull
  '<rootDir>/node_modules'
 ],
 testMatch: [
  '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
 ]
}

부트스트랩 vue를 글로벌 플러그인으로 추가하는 경우:

Vue.use(BootstrapVue);

그리고 테스트에서는 다음 팁을 따르는 것이 좋습니다.

https://vue-test-utils.vuejs.org/guides/common-tips.html#applying-global-plugins-and-mixins

여기에서는, 다음의 기능을 사용하는 방법에 대해 설명하고 있습니다.createLocalVue()앱과 동일한 글로벌 구성으로 설정합니다.

import { createLocalVue } from '@vue/test-utils'

// create an extended `Vue` constructor
const localVue = createLocalVue()

// install plugins as normal
localVue.use(BootstrapVue)

// pass the `localVue` to the mount options
mount(Component, {
  localVue
})

컴포넌트가 올바르게 등록되어야 합니다.

다음과 같은 컴포넌트를 스터브할 수도 있습니다.

const wrapper = mount(Login, {
  mocks: {
    $t: () => 'Connexion' // i18N
  },
  stubs: {
    BCol: true
  }
});

Chrismarx 답변을 확장합니다.

다음 예시는 에서 사용되는vue/nuxt에의 신청.bootstrap-vue컴포넌트 테스트 중FormInput.vue몇 가지 요소를 가지고 있다bootstrap-vue, 다음과 같은 에러가 발생하고 있습니다.Unknown custom element: <b-form-input>그리고.Unknown custom element: <b-col>그리고.Unknown custom element: <b-row>

문서에서는 슬롯 및 커스텀컴포넌트의 사용 예를 나타냅니다.나는 실수를 만회하기 위해 다음과 같이 했다.주의:bootstrap-vueImport 및stubs섹션:

import { /* mount, */ shallowMount } from '@vue/test-utils'
import { BRow, BCol, BFormInput } from 'bootstrap-vue'
import FormInput from './FormInput.vue'

describe('FormInput test', () => {
  test('is a Vue instance', () => {
    const wrapper = shallowMount(FormInput, {
      stubs: {
        // used to register custom components
        'b-form-input': BFormInput,
        'b-row': BRow,
        'b-col': BCol,
      },
    })
    expect(wrapper.vm).toBeTruthy()
  })
})

각 테스트에서 부스트랩 vue의 모든 컴포넌트를 매우 비효율적으로 Import하는 것을 볼 수 있습니다.

Import가 모두 포함된 파일을 추가하고 jest config 파일에 추가할 수 있습니다.

jest.config.displays

...
setupFiles: ['./jest/loadConfig.js'],
...

loadConfig.js

import Vue from 'vue';
import GlobalComponents from './plugins/globalComponents';
import BootstrapVue from 'bootstrap-vue';
Vue.use(BootstrapVue);
Vue.use(GlobalComponents);

글로벌 컴포넌트용 플러그 인을 종료합니다.

global Components.js

import { BRow, BCol } from 'bootstrap-vue'

const GlobalComponents = {
  install(Vue) {
    Vue.component('b-row', BRow);
    Vue.component('b-col', BCol);
  }
};

export default GlobalComponents;

여기에는 두 가지 옵션이 있습니다.먼저, 만약 당신이localVue인스턴스를 사용하여 bootstrap-vue 구성 요소를 글로벌 개체로 등록해야 합니다.localVue.component("b-breadcrumb", BBreadcrumb)

에 대해 언급하겠습니다.b-breadcrumb마치 부스트랩뷰의 구성요소의 일부인 것처럼요.

const localVue = createLocalVue()
localVue.component("b-breadcrumb", BBreadcrumb)
mount(CustomComponent, {
  // Some options
})

번째, 안 안 쓰면 안 돼요.localVue에서는 이 를 다음과 같이 마운트할 수 .

mount(CustomComponent, {
  // Some options
  components: {
    BBreadcrumb
  },
})

에 요요문문문문 there there there there there를 사용하면 요.localVue마운트 방식의 인스턴스 구성 요소 옵션이 작동하지 않습니다.

하고 bootstrap-vue를 사용하여 을 회피할 수 .stubs마운트 메서드의 옵션.

mount(CustomComponent, {
  stubs: ["b-breadcrumb"]
})

마운트 옵션에 대한 자세한 내용은 여기를 클릭하십시오.

언급URL : https://stackoverflow.com/questions/51536537/running-jest-with-bootstrap-vue

반응형