使用注释对代码进行单元测试。GenAI LIVE!| 2025年6月4日

2025-06-10

使用注释对您的代码进行单元测试。

GenAI LIVE! | 2025年6月4日

Supabase,我们喜欢编写尽可能少的代码,因此我们决定将单元测试与支持 VSCode 的 IntelliSense 的相同 JSDoc 注释相结合。

JSDoc 简介

如果你以前没听说过JSDoc,你可能见过它。它是 JavaScript 方法或类上方的注释,如下所示:

/**
 * 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
}
Enter fullscreen mode Exit fullscreen mode

@example 标签

JSDoc 有一个标签,@example它向开发人员展示如何使用记录的项目。

/**
 * 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
}
Enter fullscreen mode Exit fullscreen mode

虽然结构略有不同,但这与Elixir 的 doctests非常相似。Elixir 还有一个额外的好处,你可以使用这些注释来运行测试:

Elixir 文档测试
“4 个文档测试”

因此我们认为使用 Javascript 实现相同的功能会非常酷:@supabase/doctest-js

Doctest-JS 使用与 Elixir 的 Doctests 非常相似的格式,用于//=>指定返回值。

/**
 * @example sum(1, 2)
 * //=> 3
 */
Enter fullscreen mode Exit fullscreen mode

Doctest-JS

如果您想在自己的代码上尝试一下,这很简单:

1.安装

npm install @supabase/doctest-js
Enter fullscreen mode Exit fullscreen mode

2. 编写@example注释

在您想要测试的任何函数上创建 JSDoc 样式 @example。

例如,创建一个名为的文件sum.js并添加以下代码:

/**
 * Returns the sum of 2 numbers
 *
 * @example sum(1, 2)
 * //=> 3
 */
export const sum = (a, b) => {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

3. 运行测试

在测试套件中导入 doctest 函数并将其指向文件。

例如,创建一个名为的文件,test.js并添加以下代码:

import doctest from '@supabase/doctest-js';

describe('Doctests', () => {
  // file paths are relative to root of directory
  doctest('sum.js')
})
Enter fullscreen mode Exit fullscreen mode

然后只需运行node test,您就会获得有据可查、经过测试的代码,而无需维护任何额外的代码。


您可以在我们的postgrest-js库中看到doctest-js的实际运行

文档测试

观看并标记doctest-js以了解新版本的最新动态。

观看此 repo

鏂囩珷鏉ユ簮锛�https://dev.to/supabase/use-comments-to-unit-test-your-code-4igk
PREV
使用 7 行 CSS 创建一个简单的导航栏
NEXT
Supabase:七个月的建设。