Last active
February 5, 2024 07:01
-
-
Save joshnuss/b0ea5622e7de06b9b5244fcfc751290a to your computer and use it in GitHub Desktop.
Vitest matchers for SvelteKit errors and redirections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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