How can I test my function calculateAverage
will throw an error (console.error
) when an empty array is passed?
I'm using Jest to test, but can't get it working with .toThrowError
.
calculateAverage.test.tsx:
// Imports: File
const { calculateAverage } = require('../calculateAverage');
// Calculate Average
describe('calculateAverage', () => {
// Empty Array
test('Throw Error on empty array', () => {
expect(calculateAverage([])).toThrowError('Error: Empty Array (calculateAverage)');
});
// Test #1
test('Test #1', () => {
expect(calculateAverage([1, 2, 3])).toEqual(2);
});
// Test #2
test('Test #2', () => {
expect(calculateAverage([0, 2, 4, 6, 8, 10])).toEqual(5);
});
});
calculateAverage.tsx:
// Helper Function: Calculate Average
export const calculateAverage = (array: Array<number>) => {
// Check If Data Exists
if (array.length >= 1) {
// Total
let total: number = 0;
// Iterate Over Array
let i: number = 0;
while (i < array.length) {
// Add To Total
total += array[i];
// Increase I
i++;
}
return total / array.length;
}
else {
// Error
console.error('Error: Empty Array (calculateAverage)');
}
};
Aucun commentaire:
Enregistrer un commentaire