代码之家  ›  专栏  ›  技术社区  ›  tao

如何测试vue 2中组件的根元素上的事件?

  •  0
  • tao  · 技术社区  · 6 年前

    我正在为以下组件编写单元测试:

    <template>
      <sub-component
         @foo="bar"
      />
    </template>
    <script>
    import SubComponent from './SubComponent';
    
    export default {
      name: 'MyComponent',
      components: { SubComponent },
      methods: {
        bar(payload) {
           this.$emit('baz', ...payload);
        }
      }
    }
    </script>
    

    import { shallowMount } from '@vue/test-utils';
    import _ from 'lodash';
    import MyComponent from '../../components/MyComponent';
    
    describe('MyComponent.vue', () => {
      let wrapper;
    
      beforeEach(() => {
        wrapper = shallowMount(MyComponent);
      });
    
      it('should emit baz on subcomponent foo', () => {
        const subComp = wrapper.find('sub-component-stub');
        expect(subComp.exists()).toBe(true);          // passes
    
        subComp.vm.$emit('foo');
    
        return wrapper.vm.$nextTick().then(() => {
          expect(wrapper.emitted().baz).toBeTruthy(); // does not pass;
    
          // upon logging: 
          console.log(_.isEqual(wrapper, subComp));   // => true 
        })
      })
    })
    

    这个例子过于简单,但这里的原则是我想要一个可重用的 <sub-component> (一个模态)和它周围的各种函数包装器(与模态类型执行的一个特定任务相关)映射其他功能。我不想在父组件中使用这个功能,因为它会违反DRY-我必须将它放在每个包含特定类型模态的组件中。

    <子组件> <template> . 不知怎么的,它似乎 wrapper subComp 位于同一个元素上。

    1 回复  |  直到 6 年前
        1
  •  3
  •   mickaelw    6 年前

    另一种可能是在dom中找到元素并检查根组件的发出值。

    import { shallowMount } from '@vue/test-utils'
    import MyComponent from './MyComponent.vue'
    import SubComponent from './SubComponent.vue'
    
    describe('MyComponent', () => {    
    
      it('should emit baz on subcomponent foo', () => {
        const wrapper = shallowMount(MyComponent)
        const subComponent = wrapper.find(SubComponent)
    
        expect(subComponent.exists()).toBe(true)
        expect(wrapper.emitted('baz')).toBeUndefined()
    
        subComponent.vm.$emit('foo', ['hello'])
        expect(wrapper.emitted('baz')[0]).toEqual(['hello'])
        // or expect(wrapper).toEmit('baz', 'hello') cf. below for toEmit
      })
    
    })
    

    toEmit(received, eventName, data) {
      if (data) {
        expect(received.emitted()[eventName][0]).toEqual([data])
      } else {
        expect(received.emitted()[eventName][0]).toEqual([])
      }
      return { pass: true }
    } 
    
        2
  •  0
  •   tao    6 年前

    显然,为了测试从组件的根元素发出的事件(并避免根元素同时托管这两个元素) subComp.vm wrapper.vm wrapper.vm.$children[0]

      it('should emit baz on subcomponent foo', () => {
        const subComp = createWrapper(wrapper.vm.$children[0]);
        expect(subComp.exists()).toBe(true);
        expect(wrapper.emitted().baz).toBeFalsy();
    
        subComp.vm.$emit('foo');
    
        return wrapper.vm.$nextTick().then(() => {
          expect(wrapper.emitted().baz).toBeTruthy();
        })
      })
    推荐文章