Run JSDoc style doc examples as tests within your test suite
Inspired by Elixir Doctests
Write a function with a JSDoc style documentation
/**
* Returns fairly unnecessary and uninteresting information about a string
* @param {string} string - The string of disinterest
* @return {object} Useless information
* @example
* stringData('woah')
* //=>
* {
* length: 4,
* vowels: 2,
* consonants: 2,
* }
*/
export function stringData(string) {
const vowels = string
.toLowerCase()
.split('')
.filter((char) => {
return ['a', 'e', 'i', 'o', 'u', 'y'].find((v) => char === v);
}).length;
return {
length: string.length,
vowels: vowels,
consonants: string.length - vowels,
};
}
Import the doctest function in your test suite and point it at the file.
import doctest from 'jsdoc-test';
describe('stringData Doctests', () => {
doctest('src/string/index.js'); // path is relative to root of directory
});
And this will run and test all instances of @example
in the given file
Notes:
- The only JSDoc component
you need is the
@example
. - You can have as many
@examples
as you'd like for any one function. - Example function calls and return values can span multiple lines.
- Currently only works for exported functions
By default, doctest
will use a basic chai
expect as its testing function.
it(`${functionName} should match its doc example value`, () => {
expect(actualReturnValue).to.eql(expectedReturnValue);
});
But this function can be overridden by any function that takes three arguments:
(actualValue, expectedValue, doctestObject, doctestIndex)
.
Where the doctestObject
is the parsed doctest that looks like:
{
resultString: 'titleize('WoAh')',
stringToEval: 'Woah',
}
describe('stringData Doctests', () => {
doctest('src/string/index.js', {
testingFunction: (actual, expected, doctestObject, doctestIndex) => {
if (actual === expected) console.log(functionName + ', you did it!');
else console.log('Better luck next time, ' + functionName);
},
});
});