0.0.10 • Published 5 years ago

jsdoc-test v0.0.10

Weekly downloads
8
License
MIT
Repository
-
Last release
5 years ago

JS-Doctest

Run JSDoc style doc examples as tests within your test suite

Inspired by Elixir Doctests

npm version Build Status

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

Testing Function

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);
    },
  });
});
0.0.10

5 years ago

0.0.9

6 years ago

0.0.8

6 years ago

0.0.7

6 years ago

0.0.6

6 years ago

0.0.5

6 years ago

0.0.4

7 years ago

0.0.3

7 years ago

0.0.2

7 years ago

0.0.1

7 years ago