简介
测试让你修改代码时无需担心破坏了什么。KScript 内置了测试框架,因此无需安装任何东西。测试是文件名以 .test.kscript 或 .test.ks.xml 结尾的 KScript 文件,通常放在 tests/ 文件夹中,并通过 kscript test 运行。
这是一个用于 slugify 函数的测试文件:
<!-- tests/strings.test.kscript -->
<kscript>
<import path="../lib/strings.kscript" />
<describe name="slugify">
<test name="lower-cases and joins words with dashes">
<expect value="@slugify('Hello World')" equals="'hello-world'" />
</test>
<let name="cases">[
{ text: 'One', slug: 'one' },
{ text: 'Two Words', slug: 'two-words' },
]</let>
<for each="case" in="$cases">
<test name="slug of '{$case.text}'">
<expect value="@slugify($case.text)" equals="$case.slug" />
</test>
</for>
</describe>
</kscript>// tests/strings.test.kscript
kscript {
import "../lib/strings.kscript"
describe(name: 'slugify') {
test(name: 'lower-cases and joins words with dashes') {
expect(@slugify('Hello World'), equals: 'hello-world')
}
$cases = [
{ text: 'One', slug: 'one' },
{ text: 'Two Words', slug: 'two-words' },
]
for case in $cases {
test(name: "slug of '{$case.text}'") {
expect(@slugify($case.text), equals: $case.slug)
}
}
}
}运行 kscript test,每个测试的结果都会列出;失败的测试会说明出错原因:
$ kscript test
tests/strings.test.kscript
✓ slugify › lower-cases and joins words with dashes (1 ms)
✓ slugify › slug of 'One' (0 ms)
✗ slugify › slug of 'Two Words' (0 ms)
Expected @slugify($case.text) to equal 'two-words', but it was 'two words'.
at tests/strings.test.kscript:14:7
Tests: 1 failed, 2 passed, 3 total
Files: 1 failed, 1 total
Time: 0.08s当所有测试都通过时,退出码为 0。当有测试失败、测试文件无法运行、没有匹配的测试,或文件夹中没有测试文件时,退出码为 1。当命令行或 kscript.json 有误(例如选项未知或路径不存在)时,退出码为 2。因此,kscript test 可以用来控制 CI 任务的通过或失败。退出码在所有命令中都相同。