簡體   English   中英

如何在 vue 組合 api 組件中使用 jest 進行單元測試?

[英]How to unit testing with jest in vue composition api component?

我正在用 jest 為 vue.js 中的組合 API 組件編寫單元測試。

但是我無法訪問組合 API 的 setup() 中的函數。

指標.vue

<template>
  <div class="d-flex flex-column justify-content-center align-content-center">
    <ul class="indicator-menu d-flex justify-content-center">
      <li v-for="step in steps" :key="step">
        <a href="#" @click="updateValue(step)" :class="activeClass(step, current)"> </a>
      </li>
    </ul>
    <div class="indicator-caption d-flex justify-content-center">
      step
      <span> {{ current }}</span>
      from
      <span> {{ steps }}</span>
    </div>
  </div>
</template>

<script lang="ts">
import {createComponent} from '@vue/composition-api';

export default createComponent({
  name: 'Indicator',
  props: {
    steps: {
      type: Number,
      required: true
    },
    current: {
      type: Number,
      required: true
    }
  },
  setup(props, context) {
    const updateValue = (step: number) => {
      context.emit('clicked', step);
    };
    const activeClass = (step: number, current: number) =>
      step < current ? 'passed' : step === current ? 'current' : '';
    return {
      updateValue,
      activeClass
    };
  }
});
</script>

<style></style>

Indicator.test.ts

import Indicator from '@/views/components/Indicator.vue';
import { shallowMount } from '@vue/test-utils';

describe('@/views/components/Indicator.vue', () => {  
  let wrapper: any;
  beforeEach(() => {
    wrapper = shallowMount(Indicator, {
      propsData: {
        steps: 4,
        current: 2
      }
    });
  });
  it('should return "current" for values (2,2)', () => {
    expect(wrapper.vm.activeClass(2, 2)).toBe('current');
  });
});

我在運行測試命令時遇到了這個錯誤:

類型錯誤:無法讀取未定義的屬性“vm”

我認為只需導入CompositionApi可以解決您的問題。

import CompositionApi from '@vue/composition-api'

Vue.use(CompositionApi)

我還建議默認使用jest.config.js文件對其進行初始化:

setupFiles: ['<rootDir>/tests/helpers/foo.js']

然后在您的tests/文件夾中創建helpers/文件foo.js

並在文件中:

import Vue from 'vue'
import CompositionApi from '@vue/composition-api'
Vue.use(CompositionApi)

在 nuxt.js 版本 2 @andrej-gaspar解決方案幾乎可以工作,但它拋出Cannot read property install of undefined錯誤的Cannot read property install of undefined ,因此要修復該錯誤,請執行以下操作:

jest.config.js

setupFiles: ['<rootDir>/tests/helpers/foo.js']

foo.js

import Vue from 'vue'
import * as CompositionApi from '@vue/composition-api'
Vue.use(CompositionApi)

或者,如果您使用的是@nuxtjs/composition-api

import Vue from 'vue'
import * as CompositionApi from '@nuxtjs/composition-api'
Vue.use(CompositionApi)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM