Components often contain logic for formatting data either before it is displayed on the screen or before it is sent to the API. Those cases are also good candidates for testing as they use various control flow elements that alter the course of the function.
makePayment() { if (this.isAutoPay || !this.selectedAccount || !this.state.selectedPaymentMethod || this.balanceIsInvalid()) { return; } const request = { customerId: this.state.currentCustomerId, request: { AccountNumber: this.selectedAccount.AccountNumber, PaymentInstrumentIds: [this.state.selectedPaymentMethod.Id], Amount: this.selectCurrentBalance === 'true' ? this.state.totalBalance : parseFloat(this.formApi.customDollarAmount.$modelValue) } }; return this.actions.chargePaymentInstrument(request).then(() => { if (this.state.eWalletError) { uiNotificationService.error(i18n.translate(LocaleKeys.MAKE_PAYMENT.PAYMENT_FAILURE), null, { timeOut: NOTIFICATION_TIME_LENGTH }); this.actions.resetIsMakingPayment(); } else { this.actions.unregisterUnsavedChanges('CustomerMakePaymentController.formApi'); this.goBack(); } }); };
The above example is the function that actually charges a payment instrument for a subscriber. This is code block has lots of items that make it a good candidate for testing. To start with, there are several conditions in which the function should return before doing any processing (such as if autoPay is enabled, or there is no selected payment method.)
Beyond that, there is logic in place to determine what the balance should be (either the total balance or the custom dollar amount).
Finally, once the API call is made, one of two things can happen:
- An error is displayed an the form is reset
- No error is displayed and the user is redirected to the previous page If any of those behaviors don't happen, then make payment will have a bug.
Tests exist in the make.payment.component.spec.js file inside the customer care project.
describe('When making a payment', () => { function addPaymentStateToControl(controller, opts = {}) { controller.state.selectedPaymentMethod = { Id: 2 }; controller.selectedAccount = { AccountNumber: '123' }; controller.state.totalBalance = 100.00; controller.selectCurrentBalance = opts.selectCurrentBalance || 'true'; } it('Should call the chargePaymentInstrument action', () => { const ctrl = createController(); addPaymentStateToControl(ctrl); ctrl.makePayment(); expect(fakeActions.chargePaymentInstrument.called).to.be.true; }); it('Should use the customer id when charging', () => { const ctrl = createController(); addPaymentStateToControl(ctrl); ctrl.makePayment(); const request = fakeActions.chargePaymentInstrument.args[0][0]; expect(request.customerId).to.eql(1); }); ... });
There are more tests for that function (represented by the ellipsis) but this shows examples of how the functionality is tested. Verifying that a user was charged, and verifying that the correct customer id was passed to the action.