开玩笑,预期的模拟函数已被调用,但未调用

时间:2019-02-11 18:00:32

标签: unit-testing vue.js jestjs

在过渡组上呈现VueJS组件时测试生命周期方法。

当组件在以下VueJS组件的过渡组上进行渲染时,我一直在为生命周期方法编写测试,但在使该组件正常工作方面我进展甚微,并希望就此提出建议。我还尝试过在浅层安装和组件安装之间进行切换,尽管这似乎没有什么区别。

import { shallowMount } from '@vue/test-utils';
import StaggeredTransition from '../src/index';

const staggeredTransitionWrapper = componentData => 
    shallowMount(StaggeredTransition, {
      ...componentData,
});

const staggeredTransition = staggeredTransitionWrapper();

describe('StaggeredTransition.vue', () => {
  it('should render a staggered transition component', () => {
    expect(staggeredTransition.element.tagName).toBe('SPAN');

    expect(staggeredTransition.html()).toMatchSnapshot();
  });

  it('should mock calling the enter method', () => {
    const enterMock = jest.fn();

    StaggeredTransition.methods.enter = enterMock;

    const staggeredTransitionWrapper2 = componentData => 
    shallowMount(StaggeredTransition, { ...componentData });

    const staggeredTransition2 = staggeredTransitionWrapper2({
       slots: {
       default: '<h1 :key="1">Staggered transition test</h1>',
      },
    });

    expect(enterMock).toBeCalled();
  });
});

StaggeredTransition组件的代码

  <template>
    <transition-group
      :tag="tag"
      :name="'staggered-' + type"
      :css="false"
      appear
      @before-enter="beforeEnter"
      @enter="enter"
      @leave="leave"
    >
      <slot />
   </transition-group>
</template>

<script>
const { log } = console;

export default {
  name: 'StaggeredTransition',

  props: {
    type: {
      type: String,
      options: ['fade', 'slide'],
      required: false,
      default: 'fade',
    },

    tag: {
      type: String,
      required: false,
      default: 'div',
    },

    delay: {
      type: Number,
      required: false,
      default: 100,
    },
  },

  methods: {
    beforeEnter(el) {
      console.log('beforeEnter');
      el.classList.add(`staggered-${this.type}-item`);
    },

    enter(el, done) {
      console.log('enter');

      setTimeout(() => {
        el.classList.add(`staggered-${this.type}-item--visible`);
        done();
      }, this.getCalculatedDelay(el));
    },

    leave(el, done) {
      console.log('leave');

      setTimeout(() => {
        el.classList.remove(`staggered-${this.type}-item--visible`);
        done();
      }, this.getCalculatedDelay(el));
    },

    getCalculatedDelay(el) {
      console.log('getCalculatedDelay');

      if (typeof el.dataset.index === 'undefined') {
        log(
          'data-index attribute is not set. Please set it in order to 
make the staggered transition working.',
        );
      }

      return el.dataset.index * this.delay;
    },
  },
};
</script>

0 个答案:

没有答案