Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Last active February 5, 2024 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshnuss/b0ea5622e7de06b9b5244fcfc751290a to your computer and use it in GitHub Desktop.
Save joshnuss/b0ea5622e7de06b9b5244fcfc751290a to your computer and use it in GitHub Desktop.
Vitest matchers for SvelteKit errors and redirections
import { expect } from 'vitest'
expect.extend({
async toError(promise, status, message=null) {
try {
await promise
return { pass: false, message: () => 'Expected an error to be raised.'}
} catch (actual) {
if (actual?.constructor?.name !== 'HttpError') {
return {
pass: false,
message: () => 'Object is not an HttpError'
}
}
if (actual.status !== status) {
return {
pass: false,
message: () => `Expected an error with status ${status}, but got ${actual.status}`
}
}
if (message && actual.body.message !== message) {
return {
pass: false,
message: () => `Expected an error with message "${message}", but got "${actual.body.message}"`
}
}
return { pass: true }
}
},
async toRedirect(promise, status, location) {
try {
await promise
return { pass: false, message: () => 'Expected a redirection to be raised.'}
} catch (actual) {
if (actual?.constructor?.name !== 'Redirect') {
return {
pass: false,
message: () => 'Object is not a Redirect'
}
}
if (actual.status !== status) {
return {
pass: false,
message: () => `Expected a redirect with status ${status}, but got ${actual.status}`
}
}
if (location && actual.location !== location) {
return {
pass: false,
message: () => `Expected a redirect to location "${location}", but got "${actual.location}"`
}
}
return { pass: true }
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment