javascript / beginner
Snippet
Verifying Currency Formatter Utility with Unit Tests
Pure JavaScript helper functions that perform data transformation should be isolated and verified with unit tests. Testing both the happy path (valid numbers) and edge cases (strings, NaN) ensures the function behaves predictably across all components that consume it.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { describe, it, expect } from 'vitest';export function formatCurrency(amount, currencySymbol = '€') {if (typeof amount !== 'number' || Number.isNaN(amount)) {return '0.00 ' + currencySymbol;}return `${amount.toFixed(2)} ${currencySymbol}`;}describe('formatCurrency', () => {it('formats positive numbers with default currency', () => {const result = formatCurrency(19.99);expect(result).toBe('19.99 €');});it('handles invalid non-number input fallback', () => {const result = formatCurrency('invalid');expect(result).toBe('0.00 €');});});
vue
Breakdown
1
if (typeof amount !== 'number' || Number.isNaN(amount))
Guards against non-number types or NaN values before calling number methods.
2
expect(result).toBe('19.99 €');
Asserts that the function output matches the expected formatted currency string.