Custom matchers and snapshot serializers to enhance vitest.
npm install -D @altano/vitest-plugins
Modify vite.config.ts / vitest.config.ts:
export default defineConfig({
test: {
setupFiles: [
"@altano/vitest-plugins/matchers",
// ...
],
// ...
},
});
Add matcher types to your tsconfig.json (if using TypeScript):
{
"compilerOptions": {
"types": ["@altano/vitest-plugins/matchers"]
}
}
Modify vite.config.ts / vitest.config.ts:
export default defineConfig({
test: {
setupFiles: [
"@altano/vitest-plugins/serializers",
// ...
],
// ...
},
});
NOTE: You can pick and choose what to install: the matchers and serializers don't depend on each other.
Will format the contents of a vfile using Prettier (auto-detecting the type from the vfile's filename), e.g.
FormattedVFile {
"cwd": "<cwd>",
"data": {},
"history": [
"tests/unit/__fixtures__/basic/input.js",
],
"map": undefined,
"messages": [],
"value": "function face() { }"
}
Will replace any instances of process.cwd()
with <cwd>
in the snapshot. Useful when serializing strings that contain absolute paths, since those will be different on other machines running the tests.
Vitest's error matchers let you match against the error message, but not the rest of the Error object:
-
toThrow(error?)
- error is thrown (docs) -
toThrowErrorMatching[Inline]Snapshot
- an error exactly matches a snapshot (docs)
If you want to assert anything more complicated (e.g. an error contains some substring in the stack) then you'll need these custom matchers:
Verify any part of an error object (e.g. the stack):
expect(new Error("face")).toMatchError(
expect.objectContaining({
stack: expect.stringContaining("readme.spec.ts"),
}),
);
Verify any part of a thrown error object (e.g. the stack):
expect(() => {
throw new Error("face");
}).toThrowErrorMatching(
expect.objectContaining({
stack: expect.stringContaining("readme.spec.ts"),
}),
);
Verify the realpath (canonical path) of expected. More lenient than a string check when dealing with logical paths, symlinks, etc.
expect("/private/some/path").toBePath("/some/path");
Verify a file exists
expect(import.meta.filename).toBeFile();
Verify a directory exists
expect("/").toBeDirectory();
Verify that the given path matches the contents of another file
expect("/some/file.txt").toEqualFile("/other/file.txt");