Supabase Supabase Updated on ・2 min read

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
``````

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 doctest 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 doctest-js in action over at our postgrest-js library: Watch and star doctest-js to keep updated about new releases. ### Discussion  Jesse Phillips

I think it is unfortunate that the languages haven't learned to make this an integral part of the language.

D made it possible for unittests to become examples, included in the generated documentation. Though uncompiled examples could also be added.

``````/**
* Returns the sum of 2 numbers
*/
auto sum(int a, int b) {
return a + b;
}
///
unittest {
assert(sum(1, 2) == 3);
}
``````  