I am new to unit testing, and would like to check if any line of code to contain double loop specifically.
I am currently studying at bootcamp and they somehow check if my solution contains specific loop (like while loop) or if I used nested loop as below.
Test Code
function () {
expect(DOUBLE_LOOP_EXP.test(funcBody)).to.be.equal(true);
}
To clarify, below is my function that's been tested through above criterion;
function makePermutations(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
for (let j = 0; j < str.length; j++) {
result += str[i] + str[j] + ',';
}
}
return result.slice(0, result.length - 1);
}
module.exports = makePermutations;
Unfortunately, there's no way to know whats inside that DOUBLE_LOOP_EXP.test. Please advise.
A regexp can be something like:
/for\s*\([^;]+;[^;]+;[^;]+\)\s*{?\s*for\s*\([^;]+;[^;]+;[^;]+\)/
It's incorrect to use regexps for this because they are unaware of language syntax and can result in false positive or negative, e.g. match comments or get stuck on them.
This requires to parse JavaScript syntax. E.g. with this library that allows to query AST generated by popular Esprima parser (a playground):
const ast = esprima.parse(makePermutations.toString());
const selector = esquery.parse('ForStatement ForStatement');
const nestedFor = esquery.match(ast, selector);
expect(nestedFor.length).toBe(1);
And considering that the question applies to testing, there's never a need to so this in unit tests - unless you test a compiler that generated this code.
There may be a need to assert implementation details, but not to this degree. From unit test perspective, it doesn't matter if there are for
loops. If the function doesn't involve other units and doesn't do side effects, the test should be performed by specifying expected input and output:
expect(makePermutations('abc')).toBe('aa,ab,ac,ba,bb,bc,ca,cb,cc');
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments