I am looking to create unit tests for a REST API built with SvelteKit, but most of the available resources focus on testing svelte components. Additionally, I prefer to avoid using Playwright as I do not require browser testing and want to steer clear of dealing with extensive tool setups and additional files.
Is there a recommended approach for testing an SvelteKit REST API?
Is it considered good practice to have the .test.ts
file in the same folder as the respective route?
Currently, my SvelteKit skeleton app follows this directory structure:
src/
routes/
issues/
+server.ts
issues.test.ts
My intention is to have a .test.ts
file for each API endpoint.
In my vite.config.ts
:
/** @type {import('vite').UserConfig} */
export default defineConfig({
plugins: [sveltekit()],
test: {
include: ['src/**/*.{test,spec}.{js,ts}'],
},
});
To start off, I have created a simple test in issues.test.ts
:
describe('/issues', () => {
it('GET', async () => {
fetch('/issues').then((response) => {
expect(response.status).toBe(200);
});
});
// ···
});
However, I realized that I need the server running in order for the tests to send the fetch request to a valid destination. Initially, I assumed Vitest would handle this automatically, but that is not the case. Therefore, I now have to run npm run dev
before executing the tests, which I find slightly inconvenient.