15

我正在用 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>

指标.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');
  });
});

我在运行测试命令时遇到了这个错误:

TypeError:无法读取未定义的属性“vm”

4

3 回答 3

15

我认为简单的导入CompositionApi应该可以解决您的问题。

import CompositionApi from '@vue/composition-api'

Vue.use(CompositionApi)
于 2020-03-03T15:25:11.573 回答
2

我还建议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)

通过这种方式,它可用于每个测试文件:)

于 2021-09-06T11:39:51.063 回答
0

在 nuxt.js 版本 2@andrej-gaspar解决方案几乎可以工作,但它会引发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)
于 2021-11-13T07:50:37.490 回答