Skip to content
tezvyn:
Menu

Testing SvelteKit load Functions

MediumHow cards are made

A SvelteKit load function consumes a request event and returns page data. Unit test it by mocking the event object in Vitest, not by mounting the page. Never test it through component rendering, because load runs before the component initializes.

Why it exists

SvelteKit pages and layouts depend on load functions to supply data before any component renders. As applications grow, these functions accumulate business logic like authentication checks, header parsing, database queries, and data transformations. Without a way to test this logic in isolation, developers are forced to rely on slow end-to-end tests or manual UI clicking to catch bugs in data fetching. Testing load functions directly was introduced to give fast, deterministic feedback on the server-side logic that powers routes.

The mental model

Think of a load function as a controller method in a traditional web framework. It receives a request context, performs work, and returns a data payload. The difference is that SvelteKit hides this inside the framework routing layer. Your job when testing is to treat it like a function with an awkward input type: you construct the minimal request event it needs, call the function, and assert on the returned object. You are not testing the page component, and you are not testing the browser. You are testing the data contract between the server and the UI.

How it works

In a Vitest unit test, import the load function from its module. Build a fake event object containing only the properties your code touches. For a universal load in +page.js, this usually includes url, params, and fetch. For a server load in +page.server.js, you will also need locals, cookies, and possibly request. Mock fetch on the event to return standard Web Response objects with the JSON your route expects. Invoke load with this fake event and await the result. Assert that the returned object contains the correct keys, shapes, and error states. If your load redirects or throws, assert against those behaviors as well.

When to use it

Use isolated load tests when the function contains conditional logic, authorization rules, or data mapping that you want to exercise across many scenarios. It is also valuable when the upstream APIs are slow or flaky and you need deterministic tests that run in milliseconds. If your load function is a critical dependency for multiple pages, unit testing it protects every consumer from breaking changes.

When not to use it

Do not write unit tests for load functions that are thin proxies making a single fetch with no logic. In those cases, the integration test or the API contract test already covers the behavior. Also avoid unit testing when your mocks become so elaborate that they replicate SvelteKit internals; brittle mocks that break on framework upgrades are a signal that an integration test or a real request test is the better tool.

One canonical example

Imagine a +page.server.js load that reads a user object from locals.user, calls fetch with an authorization header, and returns an account balance. In your Vitest test, create an event where locals.user is an object with an id and a token. Set event.fetch to a stub that resolves to a Response containing JSON with balance and currency. Call load with this event and assert that the returned account object matches the expected shape. If the user is missing, assert that the load throws a redirect or returns an error object depending on your implementation. This test runs in milliseconds and never needs a browser.

Interview question

When unit testing a SvelteKit load function with conditional logic, which approach aligns with best practices?

  • a.Import the load function directly, build a minimal fake event, and assert on its return value.Correct
  • b.Use a browser automation tool to test the function because it depends on request context.
  • c.Mock SvelteKit's router and internal request pipeline to simulate a full page request.
  • d.Mount the page component and inspect the rendered output to verify the data.
Why?

The card instructs you to treat a load function as a standalone controller method by importing it directly, constructing a minimal fake event, and asserting on the returned data. Mounting the page component is incorrect because load runs before the component initializes, and mocking framework internals is discouraged because it creates brittle tests that break on upgrades.

Just read this? Test yourself on what you have been reading.

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Every open role lists the topics its interview covers, so you can prepare for the real thing rather than guessing.

See open roles