Use Comments to Unit Test Your Code [A How-To Guide]

Written by kiwicopple | Published 2020/03/01
Tech Story Tags: javascript | testing | unit-testing | documentation | nodejs | unit-test-for-code | comments-in-programming | intro-to-jsdoc

TLDR Use Comments to Unit Test Your Code [A How-To Guide] At Supabase we love writing as little code as possible. We decided to combine our unit tests with the same JSDoc comments that power VSCode's IntelliSense. Elixir has the additional benefit that you can use these comments to run your tests: @supabase/doctest-js. You can see it in action over at our postgrest-js library: The library uses a similar format to Elixir's Doctests.via the TL;DR App

At Supabase we love writing as little code as possible, so we decided to combine our unit tests with same JSDoc comments that power VSCode's IntelliSense.

Intro to JSDoc

If you've never heard of JSDoc before, you've probably seen it. It's the comments that go above a Javascript method or class like this:
/**
 * Returns the sum of 2 numbers
 * @param {number} a The first number
 * @param {number} b The second number
 */
export const sum = (a, b) => {
  return a + b
}

The @example tag

JSDoc has a tag,
@example
, which shows a developer how to use a documented item.
/**
 * Returns the sum of 2 numbers
 * @param {number} a The first number
 * @param {number} b The second number
 * @example
 * // returns 3
 * sum(1, 2)
 */
export const sum = (a, b) => {
  return a + b
}
Although the structure is a bit different, this is very similar to Elixir's doctests. Elixir has the additional benefit that you can use these comments to run your tests:
"4 doctests"
So we decided it would be pretty cool to implement the same functionality with Javascript: @supabase/doctest-js.
Doctest-JS uses a very similar format to Elixir's Doctests, using //=> to specify return values.
/**
 * @example sum(1, 2)
 * //=> 3
 */

Doctest-JS

If you want to try this on your own code, it's very simple:
1. Install
npm install @supabase/doctest-js
2. Write @example comments
Create a JSDoc style @example on any functions that you want tested.
For example, create a file called
sum.js
and add this code:
/**
 * Returns the sum of 2 numbers
 *
 * @example sum(1, 2)
 * //=> 3
 */
export const sum = (a, b) => {
  return a + b
}
3. Run the tests
Import the doctest function in your test suite and point it at the file.
For example, create a file called,
test.js
and add this code:
import doctests from '@supabase/doctest-js';

describe('Doctests', () => {
  // file paths are relative to root of directory
  doctest('sum.js')
})
And then simply run
node test
and you get well documented, tested code, without having to maintain any additional code.
You can see it in action over at our postgrest-js library:
Watch and star doctest-js to keep updated about new releases.

Published by HackerNoon on 2020/03/01