Модульный тест для функции ипотечного калькулятора - PullRequest
0 голосов
/ 02 ноября 2018

Я написал эту функцию, которая рассчитывает платеж по ипотеке на основе стоимости дома, первоначального взноса, срока ипотеки (срока кредита) и годовой процентной ставки. Я хочу проверить функцию calculatePayment, чтобы убедиться, что вывод правильный. Я выбрал Jest, но любые другие инструменты тестирования работают. Как мне написать тест для этой функции?

function calculatePayment() {

    var houseCost = parseFloat(document.getElementById("houseCost").value);
    var downPayment = parseFloat(document.getElementById("downPayment").value);

    var termOfLoan = parseFloat(document.getElementById("termOfLoan").value);

    var annualInterestRate = parseFloat(document.getElementById("annualInterestRate").value);
    var principal = houseCost - downPayment;
    var percentageRate = annualInterestRate / 1200;
    var lengthOfLoan = 12 * termOfLoan;
    var monthlyPayment = (principal * percentageRate) / (1 - (Math.pow((1 + percentageRate) , lengthOfLoan * -1)));
    monthlyPayment = monthlyPayment.toFixed(2);
    document.getElementById("payment").value = monthlyPayment;

};

Кроме того, если есть лучший способ рефакторинга, я был бы признателен за это

1 Ответ

0 голосов
/ 02 ноября 2018

Юнит тест-тест юнитов. сейчас у вас есть одна полная функция.

Разделите вашу функцию на подфункции и протестируйте их и комбинированные эффекты.

Тогда вы действительно можете проверить свои юниты.

Это просто очень простой пример. Используйте ваш набор модульных тестов по максимуму, убедитесь, что вы также тестируете исключения (что если кто-то, например, введет fizzlefup вместо числа).

function getFloatFromInput(inputId) {
   return parseFloat(document.getElementById(inputId).value);
}
function getHouseCost() {
    return getFloatFromInput("houseCost");
}
function getDownPayment() {
    return getFloatFromInput("downPayment");
}
function getTermOfLoan() {
    return getFloatFromInput("termOfLoan");
}
function getAnnualInterestRate() {
    return getFloatFromInput("annualInterestRate");
}
function calculatePrincipal(houseCost, downPayment) {
    return houseCost - downPayment;
}
function calculatePercentageRate(annualInterestRate) {
    return annualInterestRate / 1200;
}
function calculateLengthOfloan(termOfLoan) {
    return 12 * termOfLoan;
}
function calculateMonthlyPayment(principal, percentageRate, lengthOfLoan) {
    return ((principal * percentageRate) / (1 - (Math.pow((1 + percentageRate) , lengthOfLoan * -1)))).toFixed(2);
}

function calculatePayment() {

    var houseCost = getHouseCost();
    var downPayment = getDownPayment();

    var termOfLoan = getTermOfLoan();

    var annualInterestRate = getAnnualInterestRate();
    var principal = calculatePrincipal(houseCost, downPayment);
    var percentageRate = calculatePercentageRate(annualInterestRate);
    var lengthOfLoan = calculateLengthOfloan(termOfLoan);
    var monthlyPayment = calculateMonthlyPayment(principal, percentageRate, lengthOfLoan);
    document.getElementById("payment").value = monthlyPayment;
};

function test() {
    var assertEquals = function(expected, actual) {
      if(expected === actual) {
        console.log(".");
        return;
      }
      throw new Error('Expecting ' + expected +' received '+ actual);
    }
    var tests = [];
    tests.push(function() {
        document.getElementById('houseCost').value = 1;
        var value = getFloatFromInput('houseCost');
        assertEquals(parseFloat("1"),value);
    });
    tests.push(function() {
        document.getElementById('houseCost').value = 1;
        var value = getHouseCost();
        assertEquals(parseFloat("1"),value);
    });
    tests.push(function() {
        document.getElementById('downPayment').value = 1;
        var value = getDownPayment();
        assertEquals(parseFloat("1"),value);
    });
    tests.push(function() {
        document.getElementById('termOfLoan').value = 1;
        var value = getTermOfLoan();
        assertEquals(parseFloat("1"),value);
    });
    tests.push(function() {
        document.getElementById('annualInterestRate').value = 1;
        var value = getAnnualInterestRate();
        assertEquals(parseFloat("1"),value);
    });
    tests.push(function() {
        var value = calculatePrincipal(10.5, 5.3);
        assertEquals(5.2, value);
    });
    tests.push(function() {
        var value = calculatePercentageRate(1200);
        assertEquals(1, value);
    });
    tests.push(function() {
        var value = calculateMonthlyPayment(1,1,1);
        assertEquals((2.0).toFixed(2), value);
    });
    tests.push(function() {
        document.getElementById('houseCost').value = 1;
        document.getElementById('downPayment').value = 0;
        document.getElementById('termOfLoan').value = 1;
        document.getElementById('annualInterestRate').value = 1;
        calculatePayment()
        assertEquals("0.08",document.getElementById('payment').value);
    });
    for(var c=0;c< tests.length;c++) {
         tests[c]();
    }
    
}
test();
<label for="houseCost">houseCost</label><input type="text" id="houseCost"><BR/>
<label for="downPayment">downPayment</label><input type="text" id="downPayment"><BR/>
<label for="termOfLoan">termOfLoan</label><input type="text" id="termOfLoan"><BR/>
<label for="annualInterestRate">annualInterestRate</label><input type="text" id="annualInterestRate"><BR/>
<BR/>
<label for=""></label>
<input type="text" id="payment">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...