【问题标题】:how to mock this.$refs.form.validate in vue如何在 vue 中模拟 this.$refs.form.validate
【发布时间】:2019-04-23 23:21:17
【问题描述】:

我有一个 vue 代码,我根据 this.$refs.form.validate 执行一些操作 我想为它写一个测试......但不知道如何模拟 this.$refs.form.validate?我只写了基本的..有人能指出我正确的方向吗?我正在使用 Vue+Jest

methods: {
        sayHello () {

          if (this.$refs.form.validate()) {
            //code goes here
    }

有没有办法让它返回 false 和 true?

【问题讨论】:

    标签: vue.js jestjs


    【解决方案1】:

    创建一个存根

    const VueFormStub = {
     render: () => {},
     methods: {
      validate: () => {}
     }
    }
    

    然后在你的包装器中像这样添加它

    const wrapper = shallowMount(VueFile, {
     stubs: {
      'v-form': VueFormStub
     }
    })
    

    【讨论】:

      【解决方案2】:

      当我们在测试中挂载组件时,$refs 似乎在 mocks 属性中不起作用。但是,如果我们这样做,它会起作用

      const wrapper = mount(SidePanel);
      wrapper.vm.$refs.checkbox = [{ focused: false }, { focused: true }];
      

      所以当组件做这样的事情就可以了

      console.log(this.$refs.checkbox[0].focused);
      

      【讨论】:

        【解决方案3】:

        你需要使用 jest 方法jest.fn() 来模拟你的函数。就像这样const foo = jest.fn()。如果这个 fn 被调用了,你需要测试一下。

        【讨论】:

        • 写下这个 ref 组件的stub 并注意里面的这个 validate 方法。接下来在安装组件时使用此存根。 stubs: { form: { render(h) { return h('div') }, methods: { validate() {} } } }
        猜你喜欢
        • 2020-03-08
        • 2014-02-20
        • 2022-11-11
        • 1970-01-01
        • 2020-04-25
        • 1970-01-01
        • 1970-01-01
        • 2019-06-22
        • 2020-09-19
        相关资源
        最近更新 更多