Some checks failed
Deploy to GitHub Pages / build-and-deploy (push) Has been cancelled
93 lines
3.1 KiB
JavaScript
93 lines
3.1 KiB
JavaScript
// Unit tests for RPN stack operations
|
|
// These tests should fail initially since the rpn-calculator module doesn't exist yet
|
|
|
|
function testRPNStackOperations() {
|
|
try {
|
|
// This will fail since rpn-calculator.js doesn't exist yet
|
|
const rpnCalc = new RPNCalculator();
|
|
|
|
// Test push operation
|
|
rpnCalc.push(1);
|
|
rpnCalc.push(2);
|
|
rpnCalc.push(3);
|
|
|
|
const stack = rpnCalc.getStack();
|
|
if (stack.length !== 3 || stack[0] !== 1 || stack[1] !== 2 || stack[2] !== 3) {
|
|
throw new Error('RPN push operation failed: stack does not contain expected values');
|
|
}
|
|
|
|
// Test pop operation
|
|
const popped = rpnCalc.pop();
|
|
if (popped !== 3) {
|
|
throw new Error('RPN pop operation failed: did not return top value');
|
|
}
|
|
|
|
// Stack should now have 2 elements
|
|
if (rpnCalc.getStack().length !== 2) {
|
|
throw new Error('RPN pop operation failed: stack length incorrect after pop');
|
|
}
|
|
|
|
// Test multiple operations
|
|
rpnCalc.clear();
|
|
rpnCalc.push(4);
|
|
rpnCalc.push(2);
|
|
|
|
// Perform addition: 4 + 2 = 6
|
|
const addResult = rpnCalc.operate('+');
|
|
if (addResult !== 6) {
|
|
throw new Error('RPN addition operation failed: 4 2 + should equal 6');
|
|
}
|
|
|
|
// Perform subtraction: 6 - 2 = 4 (the 2 was consumed, now 6-2)
|
|
rpnCalc.push(2);
|
|
const subResult = rpnCalc.operate('-');
|
|
if (subResult !== 4) {
|
|
throw new Error('RPN subtraction operation failed: 6 2 - should equal 4');
|
|
}
|
|
|
|
// Test multiplication
|
|
rpnCalc.push(3);
|
|
rpnCalc.push(4);
|
|
const multResult = rpnCalc.operate('*');
|
|
if (multResult !== 12) {
|
|
throw new Error('RPN multiplication operation failed: 3 4 * should equal 12');
|
|
}
|
|
|
|
// Test division
|
|
rpnCalc.push(12);
|
|
rpnCalc.push(4);
|
|
const divResult = rpnCalc.operate('/');
|
|
if (divResult !== 3) {
|
|
throw new Error('RPN division operation failed: 12 4 / should equal 3');
|
|
}
|
|
|
|
// Test division by zero
|
|
rpnCalc.push(5);
|
|
rpnCalc.push(0);
|
|
const divByZeroResult = rpnCalc.operate('/');
|
|
if (!isFinite(divByZeroResult)) {
|
|
// This is expected behavior for division by zero in RPN
|
|
} else {
|
|
throw new Error('RPN division by zero should return Infinity');
|
|
}
|
|
|
|
// Test clear operation
|
|
rpnCalc.push(10);
|
|
rpnCalc.push(20);
|
|
rpnCalc.clear();
|
|
if (rpnCalc.getStack().length !== 0) {
|
|
throw new Error('RPN clear operation failed: stack not empty after clear');
|
|
}
|
|
|
|
return true; // All tests passed
|
|
} catch (error) {
|
|
return { error: error.message };
|
|
}
|
|
}
|
|
|
|
// Add test to global test collection
|
|
if (typeof addTest !== 'undefined') {
|
|
addTest('RPN Stack Operations Unit Tests', testRPNStackOperations);
|
|
} else {
|
|
console.log('Test harness not loaded. Run with test runner.');
|
|
} |