【问题标题】:How do I test that a Vue component responds to an event emitted by $root?如何测试 Vue 组件是否响应 $root 发出的事件?
【发布时间】:2017-12-31 21:39:11
【问题描述】:

我有一个组件可以监听 Vue $root 实例发出的事件。

export default {
   data() {
     return {
       name: ''
     }

   },
   methods: {
     openModal(name) {
       this.name = name
     }
   },
   mounted() {
     this.$root.$on('open-modal', name => {
       this.openModal(name);
     });
   }
 }

我还有另一个地方是我调用该事件的代码。

this.$root.$emit('open-modal', 'some-name');

如何编写一个在 $root 上调用该事件并断言该事件已被调用的单元测试?我正在使用 Vue 测试工具 https://vue-test-utils.vuejs.org/en/ 并且找不到调用事件的方法。

我试过了,但它不起作用。

it('sets the modal name on the open-modal event', () => {
    const wrapper = mount(Modal);
    wrapper.vm.$root.$emit('open-modal', 'my-modal')
    expect(wrapper.vm.$data.name).to.equal('my-modal');
  });

【问题讨论】:

  • 谢谢@RoyJ 我对监听事件的兴趣并不像我发出它那样。
  • 我认为你的发射是正确的。您没有看到数据更新的原因是处理程序在测试之前没有空闲时间来响应。

标签: unit-testing events vue.js vue-test-utils


【解决方案1】:

我知道出了什么问题。我正确地发出了事件。问题是我的组件正在使用 VueRouter 并在 openModal 方法中调用 $router.push() (我将其从代码示例中删除以保持简短)。我不得不在我的测试中存根 VueRouter 并且一切正常。这是我的测试现在的样子。

import { shallow, createLocalVue } from 'vue-test-utils';
import VueRouter from 'vue-router';
import Modal from '../cw-modal.vue';

const localVue = createLocalVue();
localVue.use(VueRouter);


describe('cw-modal component', () => {
  it('sets visible to true when the "open-modal" even is called with the modalName', () => {
    const wrapper = shallow(Modal, {
      propsData: {
        cwModalName: 'my-modal'
      },
      localVue,
      router: new VueRouter()
    });

    wrapper.vm.$root.$emit('open-modal', 'my-modal');
    expect(wrapper.vm.$data.visible).to.equal(true);
  });
}

【讨论】:

    猜你喜欢
    • 2020-04-26
    • 2021-02-04
    • 2021-09-04
    • 1970-01-01
    • 2022-01-09
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多