How To Test Simple Boolean Functions?
Im having some issues to understand testing, since I almost never find it neccessary. If I have simple functions like function isMovementOutOfBounds(newPosition) { if (newPositio
Solution 1:
At the very least
- testing helps you to make sure that your code behaves as expected under different circumstances (all kinds of inputs, including edge cases)
- testing may help you to maintain touch points between your specific module and other parts of your project
- be sure that while you develop your app it still fulfills your basic requirements
Just to give you a clue, as to which kind of tests you may perform, check out the following demo (which shows that your code is not functional, as of now):
mocha.setup('bdd')
const { expect } = chai
function isMovementForbidden(forbiddenMovements, initialPosition, newPosition) {
function isArrayInArray(arr, item) {
const item_as_string = JSON.stringify(item);
const contains = arr.some((ele) => JSON.stringify(ele) === item_as_string);
return contains;
}
const newMovement = [initialPosition, newPosition];
if (isArrayInArray(forbiddenMovements, newMovement)) {
return true;
}
return false;
}
const testSuite = [
{
descr: 'Should work for basic coordinates',
input: [[[0,0],[1,1]], [2,3], [1,1]],
output: true
},
{
descr: 'Should be able to handle empty array of forbidden movements',
input: [[], [0,0], [1,1]],
output: false
},
{
descr: 'Should be able to allow staying at current point',
input: [[1,1], [0,0], [0,0]],
output: false
}
]
describe('Basic test', ()=>{
testSuite.forEach(({input, output, descr}) =>
it(descr, ()=>{
expect(isMovementForbidden(...input)).to.equal(output)
}))
})
mocha.run()
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/8.0.1/mocha.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script><div id="mocha"></div>
Solution 2:
Testing has many benefits. You may detect unnecessary code or ideally find some errors.
In this case you could test that your functions return the correct boolean, given some edge cases or some basic input.
At least one or two simple test are enough to test the function itself, if you don't want to test too much.
Post a Comment for "How To Test Simple Boolean Functions?"