typescript - 如何在 vue 组合 api 组件中使用 jest 进行单元测试?

标签 typescript unit-testing vue.js jestjs vue-composition-api

我正在用 jest 为 vue.js 中的组合 API 组件编写单元测试。

但是我无法访问组合 API 的 setup() 中的函数。

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

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

TypeError: Cannot read property 'vm' of undefined

最佳答案

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

import CompositionApi from '@vue/composition-api'

Vue.use(CompositionApi)

关于typescript - 如何在 vue 组合 api 组件中使用 jest 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60377091/

相关文章:

typescript - 预期有 2 个参数,但得到 1.ts(2554) core.d.ts(8064, 47) : An argument for 'opts' was not provided

javascript - Nest 无法解析 UserModel 的依赖关系(?)

regex - Angular 模式验证器未按预期工作

c# - 如何使模拟第一次抛出异常并在第二次返回值

c# - 使用代码调用任务进行单元测试同步方法

angular - typescript - 类型 'userId' 上不存在属性 'unknown'

c# - 解析 HTML 片段

vue.js - 如何观察计算出的 vee-validate 错误?

javascript - Vuejs 类绑定(bind)和类插值

vue.js - 使用动态组件进行 v 验证