paint-brush
Use Comments to Unit Test Your Code [A How-To Guide] by@kiwicopple
643 reads
643 reads

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

by kiwicoppleMarch 1st, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.

Company Mentioned

Mention Thumbnail
featured image - Use Comments to Unit Test Your Code [A How-To Guide]
kiwicopple HackerNoon profile picture

At 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 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 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: .

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 library:

Watch and star to keep updated about new releases.




바카라사이트 바카라사이트 온라인바카라