javascript - 使用 bootstrap-vue 运行 jest

标签 javascript vuejs2 jestjs vue-cli bootstrap-vue

我一直在使用 vuejs 和 bootstrap-vue最近。 决定为我的项目添加单元测试。

我不太熟悉单元测试,所以我正在尝试任何我能找到的东西来理解它是如何工作的。

Login.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]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

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

所以我环顾四周,似乎我需要将这些子组件添加到父组件中。

这是 documentation对于这些组件。

我还添加了我的配置文件(与 vue-cli 3 生成的配置文件相同)

jest.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)'
 ]
}

最佳答案

如果您要将 bootstrap 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
})

然后你的组件应该正确注册-

关于javascript - 使用 bootstrap-vue 运行 jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51536537/

相关文章:

javascript - 如何在 React/Redux 计算器中编写不重复某些值的条件语句?

javascript - 在 VueJS 中从父组件中引用子组件的索引

javascript - 使用 Bootstrap-Vue 时,如何防止在单击嵌套的 b-​​input 组件时关闭 b-dropdown?

javascript - 如何强制 Jest 单元测试断言在测试结束之前执行?

javascript - AngularJS - 找不到我的 ng-controller 的名称

javascript - 使用 .on() 时传递值

javascript - 向 Jest 添加模块映射器?

javascript - 在 React 中,如何测试组件内的渲染方法

javascript - Intersection Observer 针对不同窗口大小进行微调

javascript - Vue.js API 获取