Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save davidystephenson/75556aec8b78d105fac650ebb9c811ac to your computer and use it in GitHub Desktop.
Save davidystephenson/75556aec8b78d105fac650ebb9c811ac to your computer and use it in GitHub Desktop.
const paymentAPI = {
async chargeCard(amount, cardNumber) {
// In production, this calls a real payment processor
await new Promise(resolve => setTimeout(resolve, 100));
if (cardNumber.startsWith('4')) {
return { success: true, transactionId: 'txn_123', amount };
}
throw new Error('Card declined');
}
};
async function processPayment(amount, cardNumber) {
try {
const result = await paymentAPI.chargeCard(amount, cardNumber);
return {
status: 'success',
transactionId: result.transactionId,
amount: result.amount
};
} catch (error) {
return {
status: 'failed',
error: error.message
};
}
}
describe('processPayment', () => {
// EXERCISE 1: Test that processPayment handles a successful payment correctly
// without actually calling a payment processor.
it('should handle successful payment', async () => {
// TODO: Spy/mock paymentAPI.chargeCard
const result = await processPayment(50, '4111111111111111');
// TODO: Verify chargeCard was called with (50, '4111111111111111')
// TODO: Verify result status is 'success'
// TODO: Verify result has transactionId 'txn_456'
// TODO: Restore the spy
});
// EXERCISE 2: You want to test that processPayment handles a failed payment correctly
// by throwing an error without actually failing a real payment
it('should handle payment failure', async () => {
// TODO: Spy on paymentAPI.chargeCard and mock it to reject with:
// new Error('Insufficient funds')
// const chargeSpy = jest.spyOn(...).mockRejectedValue(...)
const result = await processPayment(1000, '4111111111111111');
// TODO: Verify chargeCard was called
// TODO: Verify result status is 'failed'
// TODO: Verify result error is 'Insufficient funds'
// TODO: Restore the spy
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment