如何使用vue-test-utils和vue测试prop方法?

时间:2018-04-18 14:39:42

标签: vue.js vue-test-utils

我有一个子组件,其onBilling方法从其父级传递为prop:

我可以在单元测试中看到控制台日志被触发,但是我的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
  })

1 个答案:

答案 0 :(得分:1)

在:

onBillingValid: jest.fn()

jest.fn() already returns a mock function

所以不需要(删除它):

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

只需使用:

expect(wrapper.vm.onBillingValid).toHaveBeenCalledTimes(1)
相关问题