<!DOCTYPE html>
<html>
<head>
<!-- Mocha CSS to style the results -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.2.0/mocha.css">
<!-- Mocha framework -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.2.0/mocha.js"></script>
<script>
mocha.setup('bdd'); // minimal setup
</script>
<!-- Chai -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.js"></script>
<script>
// Make chai assert global
const assert = chai.assert;
</script>
</head>
<body>
<script>
// Function to test
function factorial(n) {
let answer = 1;
for (let i = n; i >= 1; i--) {
answer *= i;
}
return answer;
}
</script>
<!-- Script with tests -->
<script src="test.js"></script>
<!-- Show test results -->
<div id="mocha"></div>
<!-- Run tests -->
<script>
mocha.run();
</script>
</body>
</html>
actual == expected
is false
// test.js
describe("factorial", function() {
it("3 factorial is 6", function() {
assert.equal(factorial(3), 6);
});
it("4 factorial is 24", function() {
assert.equal(factorial(4), 24);
});
});
Screenshot from Chrome:
describe("factorial", function() {
const testValues = new Map([
[0, 1], [3, 6], [4, 24], [5, 120]
]);
for (let [num, answer] of testValues) {
it(`${num} factorial is ${answer}`, function() {
assert.equal(factorial(num), answer);
});
}
});
assert.equal(actual, expected)
- Checks if expected == actual
assert.strictEqual(actual, expected)
- Checks if expected === actual
assert.isTrue(value)
- Checks if value === true
assert.isFalse(value)
- Checks if value === false
assert.isNull(value)
- Checks if value
is null
assert.isNaN(value)
- Checks if value
is NaN
factorial()
returns NaN if passed
a negative number or a non-integer number (Hint: Number.isInteger()
could be helpful)