3

I have a child component which has a onBilling method passed from its parent as a prop:

I can see in my unit test the console log is getting fired, but not my assertion for the onBillingValid function is not working---- do I have to use wrapper.SetMethods? Couldn't find much documentation on passing callback methods as props, let alone testing them

<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>

Unit test:

  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 Answer 1

2

In:

onBillingValid: jest.fn()

jest.fn() already returns a mock function.

So no need to have (delete it):

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

And just use:

expect(wrapper.vm.onBillingValid).toHaveBeenCalledTimes(1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.