【问题标题】:What is this.myClick() doing in this vue js method and how could I test it?this.myClick() 在这个 vue js 方法中做了什么,我该如何测试它?
【发布时间】:2019-03-10 21:35:07
【问题描述】:

目前在 vue 代码中,我有一个页面包含以下行:

<MyButton :my-click="generateSomeValues"/>

generateSomeValues,生成值,然后在组件中的 prop 上设置这些值。

MyButton 是一个组件,在其中,它有以下内容:

    @click.prevent="myloginButtonClicked" (The button has a click event which called the code below)

然后我们就有了 props 和 a 方法:

      props: {
         myClick: {
           type: Function,
           default: undefined,
    },
  },

      methods: {
        async myloginButtonClicked() {
          if (typeof this.myClick !== 'undefined') {
            this.myClick();
          }
        }
      },

我试图了解 this.myClick() 正在做什么以及如何使用 Jest 对其进行测试。看了一下,我还以为 myClick 只是一个道具而不是方法?

【问题讨论】:

    标签: vue.js jestjs vue-component


    【解决方案1】:

    基于代码sn-p

    props: {
        myClick: {
            type: Function,
            default: undefined,
        }
    },
    

    您确实将myClick 定义为道具。它不是一种方法。然而,它是一个 prop 恰好是一个函数,这意味着它可以被调用。

    要对其进行测试,您可以使用 Mock 函数

    const mockMyClick = jest.fn(() => {});
    const wrapper = shallowMount(MyButton, {
      propsData: { myClick: mockMyClick }
    });
    const button = wrapper.find('button') // or whatever
    button.trigger('click')
    expect(mockMyClick.mock.calls.length).toBe(1);
    

    【讨论】:

    • 这是有道理的。为了确认我如何测试 myClick 的场景都被定义,即它调用 this.myClick(),然后场景或 myClick 未被定义,因此它不会调用 this.myClick()。感谢您的帮助。
    猜你喜欢
    • 2010-11-29
    • 2015-05-12
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多