iTranslated by AI
Writing Vitest tests in the same file as implementation
For example, in languages like Rust, you can write test code in the same file as the implementation.
#![allow(unused)]
fn main() {
pub fn add_two(a: i32) -> i32 {
internal_adder(a, 2)
}
fn internal_adder(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn internal() {
assert_eq!(4, internal_adder(2, 2));
}
}
There are several advantages to writing test code in the same file as the implementation:
- You can test functions that you want to keep private and don't want to export.
- Since the distance between implementation and testing is small, it's easier to write tests (I personally always split my editor screen only when writing test code).
- You can write code quickly when you want to whip up a prototype.
JavaScript does not have a language-level feature to write tests in the same file like Rust does, but there are articles describing clever ways to achieve this.
And it seems a testing tool called Vitest provides a way to write test code in the same file, so I'll give it a try.
Setting up the Vitest environment
To use Vitest, you need Vite v2.7.10 or later and Node v14 or later. Let's create a simple Vite project.
$ npm create vite -- --template vanilla-ts
Install Vitest. Version 0.6.0 or higher is required.
$ npm i vitest
Next, configure the settings. First, create a vite.config.ts file.
// vite.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
define: {
'import.meta.vitest': false,
},
test: {
includeSource: ['src/**/*.{js,ts}'],
},
})
The define option is a setting to ensure that test code is not included in the bundle file during production builds.
test.includeSource tells Vitest that the files under src are targets for testing.
Next, add the type information for import.meta.vitest to tsconfig.json.
{
"compilerOptions": {
+ "types": [
+ "vitest/importMeta"
+ ]
}
}
Writing test code
Now, let's write some test code.
const add = (a: number, b: number) => {
return a + b
}
if (import.meta.vitest) {
const { describe, it, expect } = import.meta.vitest
describe('calc', () => {
it('add', () => {
expect(add(1, 2)).toBe(3)
})
})
}
Test code is written within the if (import.meta.vitest) block. This is to ensure that the test code is removed during runtime.
Normally, when using Vitest, functions like describe and expect need to be imported, but using that method would include them in the runtime bundle. Therefore, we retrieve them from the import.meta.vitest object instead.
Now, let's run the test.
$ npx vitest
DEV v0.6.0 ~/vite-project
√ src/calc.ts (1)
Test Files 1 passed (1)
Tests 1 passed (1)
Time 5.30s (in thread 3ms, 179055.32%)
PASS Waiting for file changes...
press h to show help, press q to quit
The tests are running without any issues.
Additionally, there are likely libraries you want to use only during testing, such as lodash.cloneDeep. In such cases, writing an import statement at the top level would result in that library being included in the bundle file.
When there is a library you only want to use for testing, use dynamic imports inside the if (import.meta.vitest) block.
const add = (a: number, b: number) => {
return a + b
}
const obj = {
a: 1,
b: {
c: 2,
}
}
if (import.meta.vitest) {
const { describe, it, expect } = import.meta.vitest
const { cloneDeep } = await import('lodash-es')
const copy = cloneDeep(obj)
describe('calc', () => {
it('add', () => {
expect(add(copy.a, copy.b.c)).toBe(3)
})
})
}
References
Discussion