使用注释对您的代码进行单元测试。
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
}
@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
}
虽然结构略有不同,但这与Elixir 的 doctests非常相似。Elixir 还有一个额外的好处,你可以使用这些注释来运行测试:
![]() |
---|
“4 个文档测试” |
因此我们认为使用 Javascript 实现相同的功能会非常酷:@supabase/doctest-js。
Doctest-JS 使用与 Elixir 的 Doctests 非常相似的格式,用于//=>
指定返回值。
/**
* @example sum(1, 2)
* //=> 3
*/
Doctest-JS
如果您想在自己的代码上尝试一下,这很简单:
1.安装
npm install @supabase/doctest-js
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
}
3. 运行测试
在测试套件中导入 doctest 函数并将其指向文件。
例如,创建一个名为的文件,test.js
并添加以下代码:
import doctest from '@supabase/doctest-js';
describe('Doctests', () => {
// file paths are relative to root of directory
doctest('sum.js')
})
然后只需运行node test
,您就会获得有据可查、经过测试的代码,而无需维护任何额外的代码。
您可以在我们的postgrest-js库中看到doctest-js的实际运行:
观看并标记doctest-js以了解新版本的最新动态。
鏂囩珷鏉ユ簮锛�https://dev.to/supabase/use-comments-to-unit-test-your-code-4igk