【问题标题】:How to test prop methods with vue-test-utils and vue?如何使用 vue-test-utils 和 vue 测试 prop 方法?
【发布时间】:2018-09-28 20:45:56
【问题描述】:

我有一个子组件,它的 onBilling 方法从其父组件作为道具传递:

我可以在我的单元测试中看到控制台日志被触发,但不是我对 onBillingValid 函数的断言不起作用----我必须使用 wrapper.SetMethods 吗?找不到太多关于将回调方法作为道具传递的文档,更不用说测试它们了

<script>
export default {
  name: 'AddressForm',
  $_veeValidate: {
    validator: 'new'
  },
  props: {
    billingAddress: {
      type: Object,
      default: Object
    },
    onBillingValid: {
      type: Function,
      default: Function
    }
  },
  watch: {
    billingAddress: {
      handler(newId, oldId) {
        this.$validator.validateAll().then((result) => {
            console.log("validity of billing from address child", result)
            // notify identity parent that billing Form is valid or invalid
            this.onBillingValid(result);
        })
      },
      deep: true
    }
  },
  mounted () {
    this.$validator.localize('en-US', this.dictionary)
  }
}
</script>

单元测试:

  it('should trigger watcher and call onBillingValid when billingAddress prop is modified', () => {
    const $validator = new VeeValidate.Validator()
    const errors = {
      collect: jest.fn()
    }

    const wrapper = shallow(AddressForm, {
      mocks: { errors, $t, $validator },
      propsData: {
        billingAddress: {
          fullName: 'john doe',
          address: '',
          city: '',
          state: '',
          postalCode: ''
        },
        onBillingValid: jest.fn()
      }
    })

    const spy = jest.spyOn(wrapper.vm, 'onBillingValid')
    // trigger watcher
    wrapper.setProps({
      billingAddress: {
        fullName: 'jane doe',
        address: '',
        city: '',
        state: '',
        postalCode: ''
      }
    })
    expect(spy).toHaveBeenCalledTimes(1) // not working
  })

【问题讨论】:

    标签: vue.js vue-test-utils


    【解决方案1】:

    在:

    onBillingValid: jest.fn()
    

    jest.fn() already returns a mock function.

    所以不需要(删除):

    const spy = jest.spyOn(wrapper.vm, 'onBillingValid')
    

    只需使用:

    expect(wrapper.vm.onBillingValid).toHaveBeenCalledTimes(1)
    

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2019-04-17
      • 2019-07-16
      • 2021-04-03
      • 2018-11-09
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      相关资源
      最近更新 更多