有没有一种方法可以对Vue.js过渡进行单元测试?

3
我有一个包含动态命名转换的Vue组件。我试图找到一种方法来测试基于传递到组件中的属性设置转换名称是否正确。这是组件。

<template>
    <aside :class="['cw-vue-modal', modalSizeClass]" v-show="showModal && modalName === currentModalName">
        <transition :name="`${effect}-${speed}`" :duration="500">
            <div class="cw-vue-modal-wrap" v-show="showModal">
                <div class="cw-vue-modal-body">
                    <header>
                        <h2 v-if="currentModalTitle">{{ currentModalTitle }}</h2>
                        <a href="#" class="cw-vue-modal-close" @click.prevent="closeModal"></a>
                    </header>
                    <article :class="['cw-vue-modal-content', {'cw-vue-modal-pad' : padContent}]">
                        <slot name="content"></slot>
                    </article>
                </div>
            </div>
        </transition>
    </aside>
</template>

<script>
  import { mapGetters, mapActions } from 'vuex';

  export default {
    name: 'cw-modal',
    props: {
      modalName: {
        required: true,
        type: String
      },
      padContent: {
        required: false,
        type: Boolean
      },
      modalSize: {
        required: false,
        type: String
      },
      effect: {
        required: false,
        type: String
      },
      speed: {
        required: false,
        type: String,
        default: 'normal'
      },
      maskLight: {
        required: false,
        type: Boolean
      }
    },
    computed: {
      ...mapGetters(['showModal', 'currentModalName', 'currentModalTitle']),
      modalSizeClass() {
        if (this.modalSize === 'small') return 'cw-vue-modal-sm';
        if (this.modalSize === 'large') return 'cw-vue-modal-lg';
        return 'cw-vue-modal-md';
      }
    },
    methods: {
      ...mapActions(['closeModal'])
    }
  };
</script>

我正在使用 mocha,在配合 chia 和 avoriaz 库,编写单元测试。以下是测试代码:

it('it adds the slide slow effect', () => {
    getters = {
      showModal: () => true,
      currentModalName: () => 'my-modal',
      currentModalTitle: () => null
    };
    store = new Vuex.Store({getters});
    const wrapper = mount(Modal, {
      propsData: { modalName: 'my-modal', effect: 'slide', speed: 'slow' },
      store,
      attachToDocument: true
    });
    expect($('.cw-vue-modal-wrap')).to.have.class('slide-slow-enter-active');
  });

看起来我期望的类没有被插入到DOM中。希望能得到帮助。

谢谢。

1个回答

0

我并不确定如何在遵循最佳实践的情况下将其应用到您的项目中,但是在计算机科学中有像 invariantsassertions 这样的结构。

就像我说的一样,我也不太熟悉它,但这里有一个想法: 你可以使用这种方法,在运行测试时向 DOM 中插入不可见的 div。例如,在动画过程中将变量设置为 true ,然后在 div 标记内使用该变量的 v-bind:show="yourVar" ,并检查该元素的可见性。

我也没有在文档中找到任何“官方”方法来执行此操作,因此这个解决方法可能是唯一的方式……至少在编写其他功能测试时是我这样做的 ;)


我认为这里更重要的问题是在测试中何时能够断言动画正在发生。如果我在Chrome开发者工具中查看DOM,我可以看到动画类被添加到我的元素中,然后它们很快消失了。我认为我需要在我的测试中找到一种冻结时间的方法,并且确切地知道何时进行断言。 - Doug Steinberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接