@altano/vitest-plugins
v0.2.0
Published
Custom matchers and snapshot serializers to enhance vitest
Downloads
5,823
Readme
vitest-plugins
Custom matchers and snapshot serializers to enhance vitest.
Installation
npm install -D @altano/vitest-plugins
To install the custom matchers
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"]
}
}
To install the snapshot serializers
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.
Details
Snapshot Serializers
VFile
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() { }"
}
Absolute Paths
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.
Matchers
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:
toMatchError
Verify any part of an error object (e.g. the stack):
expect(new Error("face")).toMatchError(
expect.objectContaining({
stack: expect.stringContaining("readme.spec.ts"),
}),
);
toThrowErrorMatching
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"),
}),
);
toBePath
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");
toBeFile
Verify a file exists
expect(import.meta.filename).toBeFile();
toBeDirectory
Verify a directory exists
expect("/").toBeDirectory();
toEqualFile
Verify that the given path matches the contents of another file
expect("/some/file.txt").toEqualFile("/other/file.txt");