So i have a vue method that i need to test
in CheckoutButton.vue
createMidtransToken () {
const card = this.$store.state.payment.creditCardPayload
const options = {
onSuccess: (response) => {
// HANDLING SUCCESS
const payload = {
...this.paymentTypeChoosen,
token: response.token_id
}
this.payCheckout(payload)
},
onFailure: (response) => {
// HANDLING ERROR
const errorMessage = response.status_message
this.$alertModal.show({
show: true,
type: 'error',
title: 'Transaksi Dibatalkan',
text: errorMessage,
showButton: true,
buttonText: 'Kembali',
buttonEventExist: true,
buttonEvent: () => {
this.handleRouteError()
}
})
}
}
window.MidtransNew3ds.getCardToken(card, options)
}
in CheckoutButton.spec.js
it('Should test createMidtransToken', () => {
Object.defineProperty(window, 'MidtransNew3ds', {
getCardToken: jest.fn()
})
wrapper.vm.createMidtransToken()
expect(window.MidtransNew3ds.getCardToken).toHaveBeenCalled()
})
})
and I get an error
● Testing component CheckoutButton with stage summary › Should test createMidtransToken
TypeError: Cannot read property 'getCardToken' of undefined
362 | }
363 | }
> 364 | window.MidtransNew3ds.getCardToken(card, options)
| ^
365 | },
How do I test the createMidtransToken method so the file test can run properly?
CodePudding user response:
defineProperty
arguments are incorrect. There should be either get
function or value
value in config object in order to define a property.
Object.defineProperty(window, 'MidtransNew3ds', {
value: { getCardToken: jest.fn() }
})
There is no reason to use it here because defineProperty
is useful only for specific purposes. It can be defined either per test or in beforeEach
for all tests:
window.MidtransNew3ds = { getCardToken: jest.fn() };
And should be always cleaned in afterEach
in order to not affect other tests:
delete window.MidtransNew3ds