Introduction
Tests let you change code without worrying that you broke something. KScript has a test framework built in, so there is nothing to install. Tests are KScript files whose names end in .test.kscript or .test.ks.xml, usually kept in a tests/ folder, and kscript test runs them.
Here is a test file for a slugify function:
<!-- 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)
}
}
}
}Run kscript test, and each test's result is listed, with what went wrong for a failure:
$ 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.08sThe exit code is 0 when every test passed. It is 1 when a test failed, a test file couldn't run, no tests matched, or the folder has no test files. It is 2 when the command line or kscript.json is wrong, such as an unknown option or a path that isn't there. So kscript test can gate a CI job. Exit codes are the same for every command.