Automatically configure Vitest from your SvelteKit configuration.

Overview

vitest-svelte-kit

Automatically configure Vitest from your SvelteKit configuration.

Getting Started

Installing

In an existing SvelteKit project, run the following.

npm install --save-dev vitest vitest-svelte-kit

Configuring

Create a file called vitest.config.js:

import { extractFromSvelteConfig } from "vitest-svelte-kit"

export default extractFromSvelteConfig()

What’s Inlcuded

This package aims to emulate SvelteKit-specific behavior in a unit testing context. It does not actually run SvelteKit, but rather configures Vite in a way similar to how SvelteKit would do so.

Svelte File Support

Importing .svelte files into tests will work out of the box.

SvelteKit Modules

SvelteKit makes a number of modules available to your application.

This package will define those modules with reasonable defaults, but if you depend on their behavior its suggested you mock them using Vitest’s mocking capabilities.

Vite Configuration

Since SvelteKit is built on Vite, it allows you to pass a Vite configuration as part of your Svelte config file.

This package will use that configuration when running Vitest – meaning any custom Vite config, such as plugins, will be used in your tests.

Example

An example usage of this package can be seen here.

Stability

Vitest and SvelteKit are both under active development and are subject to breaking changes. This package aims to stay up-to-date with any upstream changes, but may introduce breaking changes as a result.

When both of these projects become stable, this package aims to follow suit.

Additional Resources

Comments
  • New experimental sveltekit config exposed

    New experimental sveltekit config exposed

    Do we need to make some changes in this plugin, because of https://github.com/sveltejs/kit/issues/5184 and https://github.com/sveltejs/kit/issues/4329 ?

    opened by sebastianrothe 7
  • Syntax errors all over the place

    Syntax errors all over the place

    Simply doing this in svelte config:

    export default () => ({vite: {}})
    

    and then in vite.config.js:

    import { extractFromSvelteConfig } from 'vitest-svelte-kit';
    
    let cfg = extractFromSvelteConfig();
    
    cfg.then(console.log); // Just the plugins added by this package
    
    export default cfg;
    

    is giving syntax errors seemingly at random:

    vite v2.9.9 building for production...
    ✓ 0 modules transformed.
    [vite-plugin-svelte] /workspace/stackoverflow_import/src/routes/__layout.svelte:180:46 RightParenthesis is expected
    file: /workspace/stackoverflow_import/src/routes/__layout.svelte:180:46
     178 |      height: 3px;
     179 |      border: 0;
     180 |      background-image: linear-gradient(to right, @primary-500, spin(@primary-500, -20), transparent);
                                                            ^
     181 |    }
     182 |    :global(.gradient-text) {
    > /workspace/stackoverflow_import/src/routes/__layout.svelte:180:46 RightParenthesis is expected
        at error (file:///workspace/stackoverflow_import/node_modules/.pnpm/[email protected]/node_modules/svelte/compiler.mjs:17691:19)
        at Parser$1.error (file:///workspace/stackoverflow_import/node_modules/.pnpm/[email protected]/node_modules/svelte/compiler.mjs:17767:9)
        at Object.read_style [as read] (file:///workspace/stackoverflow_import/node_modules/.pnpm/[email protected]/node_modules/svelte/compiler.mjs:14456:20)
        at tag (file:///workspace/stackoverflow_import/node_modules/.pnpm/[email protected]/node_modules/svelte/compiler.mjs:16817:33)
        at new Parser$1 (file:///workspace/stackoverflow_import/node_modules/.pnpm/[email protected]/node_modules/svelte/compiler.mjs:17726:21)
        at parse$3 (file:///workspace/stackoverflow_import/node_modules/.pnpm/[email protected]/node_modules/svelte/compiler.mjs:17858:20)
        at compile (file:///workspace/stackoverflow_import/node_modules/.pnpm/[email protected]/node_modules/svelte/compiler.mjs:31871:17)
        at compileSvelte2 (file:///workspace/stackoverflow_import/node_modules/.pnpm/@[email protected][email protected][email protected]/node_modules/@sveltejs/vite-plugin-svelte/dist/index.js:321:20)
        at async Object.transform (file:///workspace/stackoverflow_import/node_modules/.pnpm/@[email protected][email protected][email protected]/node_modules/@sveltejs/vite-plugin-svelte/dist/index.js:1727:25)
    [!] Error: unfinished hook action(s) on exit:
    (vite:load-fallback) load "/workspace/stackoverflow_import/.svelte-kit/runtime/client/start.js"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/__error.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/challenges/__layout.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/modules/__layout.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/about.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/api/verify/[slug].svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/challenges/[slug]/submit.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/challenges/index.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/graphql_test.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/help/ask.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/help/faq/[slug].svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/help/faq.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/help/index.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/help/questions/[slug].svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/home.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/index.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/login.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/modules/index.svelte"
    (vite:load-fallback) load "/workspace/stackoverflow_import/src/routes/signup.svelte"
    
     ELIFECYCLE  Command failed with exit code 1.
    
    opened by Explosion-Scratch 3
  • Export kit-module-emulator

    Export kit-module-emulator

    I would like to ask if it would be possible to export the kitModuleEmulator-plugin?

    I was thinking of using it in https://github.com/storybookjs/builder-vite instead of mocking the sveltekit-modules by myself.

    Thank you!

    opened by benbender 3
  • Update plugin to take in vite.config.js to Align with newer versions of Sveltekit.

    Update plugin to take in vite.config.js to Align with newer versions of Sveltekit.

    Recently Sveltekit converted from using the Svelte config file to configure Vite to using the vite.config.js making loading your own vite config in this module non functional.

    Please refer to this issue: https://github.com/sveltejs/kit/issues/5255

    What I did

    • Updated the plugin to read the vite.config.js file instead of the svelteConfig.kit.vite
    • Updated dependencies in lock

    Possible Issues

    • Do we want to allow users to inline the vite config also?
    • Don't think this solves this issue with stores
    opened by bertybot 2
  • Failed to resolve

    Failed to resolve "extends":"./.svelte-kit/tsconfig.json"

    I don't know if this the correct place to put this problem (if it is not I apologize). When setting up a project with SvelteKit where its tsconfig.json contains "extends": "./.svelte-kit/tsconfig.json", as it is present in the documentation, it breaks the tests when running vitest. If I delete this line the error does not happen.

    More specifically the error below when running vitest --run. When there are several tests, only one of them fails with this error and the others pass: image

    vitest.config.ts

    import { extractFromSvelteConfig } from 'vitest-svelte-kit';
    
    export default extractFromSvelteConfig();
    

    Is there something missing, or is this current limitation?

    opened by BeeMargarida 2
  • Typescript Support

    Typescript Support

    Currently when using this with typescript.

    ▲ [WARNING] Cannot find base config file "./.svelte-kit/tsconfig.json"
    
        tsconfig.json:2:12:
          2 │   "extends": "./.svelte-kit/tsconfig.json"
            ╵              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    

    Further if you use ts instead of js for the tests you get the following error and the tests don't run.

     FAIL  src/lib/button/button.test.ts [ src/lib/button/button.test.ts ]
    Error: failed to resolve "extends":"./.svelte-kit/tsconfig.json" in <Project path>/tsconfig.json
     ❯ resolveExtends node_modules/vite/dist/node/chunks/dep-9c153816.js:22266:11
     ❯ parseExtends node_modules/vite/dist/node/chunks/dep-9c153816.js:22250:34
     ❯ parse$e node_modules/vite/dist/node/chunks/dep-9c153816.js:22201:24
     ❯ async loadTsconfigJsonForFile node_modules/vite/dist/node/chunks/dep-9c153816.js:22547:24
     ❯ async transformWithEsbuild node_modules/vite/dist/node/chunks/dep-9c153816.js:22380:36
     ❯ async TransformContext.transform node_modules/vite/dist/node/chunks/dep-9c153816.js:22468:32
     ❯ async Object.transform node_modules/vite/dist/node/chunks/dep-9c153816.js:38334:30
     ❯ async doTransform node_modules/vite/dist/node/chunks/dep-9c153816.js:53030:29
    
    opened by ccadieux 2
  • Top level hooks support

    Top level hooks support

    Hi, first of all, thanks for the neat tool! Encountered ReferenceError: describe is not defined error while running a few tests inspired from the Svelte Vitest example which is using top level hooks.

    import { cleanup, fireEvent, render, screen } from '@testing-library/svelte'
    import Hello from '../components/Hello.svelte'
    
    describe('Hello.svelte', () => {
    

    When importing the accurate hooks, like in the vitest-svelte-kit example, tests work. Is it possible to support top level hooks ?

    opened by tommywalkie 2
  • fix: encount for the new sveltekit vite config placement

    fix: encount for the new sveltekit vite config placement

    The newest SvelteKit has 'vite' placed on a higher level, not within the 'kit' configuration. This PR fixes that, while allowing for older configurations to keep working as well.

    https://kit.svelte.dev/docs/configuration

    opened by kevtiq 1
  • Specify custom Vitest config

    Specify custom Vitest config

    Hi! Thanks for your work on this package @nickbreaton! I'm using this package with my vitest.config.js but I have existent configuration here:

    {
      plugins: [svelte({ hot: !process.env.VITEST }), Icons({ compiler: 'svelte' })],
      test: {
        watch: false,
        clearMocks: true,
        environment: 'jsdom',
        include: ['test/**/*.ts'],
        exclude: [
          'node_modules',
          'dist',
          '.idea',
          '.git',
          '.cache',
          'test/__mock__/**/*.ts',
          '.coverage',
          '.svelte-kit',
        ],
        deps: {
          inline: ['@splidejs/svelte-splide', 'msw', /@sentry/],
        },
        coverage: { reporter: ['lcovonly'], reportsDirectory: '.coverage' },
      },
    }
    

    I would like to be able to provide this config along with the one provided by the package to Vitest. Would this be possible? Thanks in advance!

    opened by EstebanBorai 1
  • Add custom vitest plugin

    Add custom vitest plugin

    I am trying to test a graphql call performed with @urql/svelte but, during the test, every call returns a [Network] fetch is not defined error; so, I would like to add the @rollup/plugin-graphql vite plugin to the configuration as shown here.

    Is there a way to add a custom plugin to this vite.config.js file:

    import { extractFromSvelteConfig } from "vitest-svelte-kit"
    export default extractFromSvelteConfig()
    

    BTW, as the graphql call works without issues when running the sveltekit application (both in SSR as in the client), so I am not sure if this is a problem of a missing plugin or a problem with vitest-svelte-kit

    opened by ufoscout 1
  • [bug] Svelte config file resolving on Windows

    [bug] Svelte config file resolving on Windows

    Helloo!

    As described in this Vite issue, there is a problem on Windows to get the file with ES modules

    There is an error like this:

    Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'

    Solution is easy, one liner,

    import {pathToFileURL} from 'url'
    
    const resolvedConfigFile = path.resolve(process.cwd(), "svelte.config.js");
    const file = pathToFileURL(resolvedConfigFile).href;
    
    
    opened by lukaszwisniewski88 1
  • Add @testing-library/jest-dom to the example

    Add @testing-library/jest-dom to the example

    What has been done:

    • Installed @testing-library/jest-dom package
    • Updated Vitest version (the older version doesn't catch the updated matchers types)
    • Moved cleanup and the matchers extending to a separate file (setupTests.ts). Also changed beforeEach to afterEach for the cleanup (to match the example in the @testing-library/svelte docs)
    • Overrode globals and setupFiles fields in the tests' setup (in svelte.config.js file)
    • Used toBeInTheDocument matcher instead of toBeDefined to check the changed and TypeScript support
    • Used getByText from the imported screen object instead of the one from the render result (here is why)
    • Fixed comments indentation in tsconfig.json
    • Added a note about @testing-library/jest-dom to README.md and fixed a typo out there
    opened by vasilii-kovalev 0
Adapter for SvelteKit apps that prerenders your site as a collection of static files for GitHub Pages

svelte-adapter-github Adapter for SvelteKit apps that prerenders your site as a collection of static files for GitHub Pages. Usage Install with npm i

null 36 Sep 20, 2022
Configure multi-pages applications and code splitting

vite-plugin-mp Configure multi-pages applications and code splitting Usage npm install vite-plugin-mp -D // vite.config.js import { defineConfig } fro

null 15 Dec 2, 2022
Small library to accomplish common tasks in Svelte/SvelteKit

svelte-utilities svelte-utilities is a small utilities library for Svelte/SvelteKit that provides features I use in almost every project, such as: Laz

null 40 Nov 25, 2022
Minimal, zero-configuration and fast solution for static site generation in any front-end framework.

Staticit - Introduction Whether you want to increase performance of your web application or improve SEO. Generally you have 2 options, use SSR (Server

Engineerhub 4 Jun 11, 2022
Production-ready fullstack Nuxt 3 starter with a well-working, opinionated configuration

sidebase sidebase is a modern, best-practice, batteries-included fullstack-app starter based on Nuxt 3 and TypeScript. With this nuxt 3 starter you ge

sidestream 392 Jan 1, 2023
Automatically detect and import components or modules

vite-plugin-autoimport Automatically detect and import components or modules. Motivation It's very common to have many components in one file as the p

Yuan Chuan 146 Dec 23, 2022
jump to local IDE source code while click the element of browser automatically.

?? Introduction A vite plugin which provides the ability that to jump to the local IDE when you click the element of browser automatically. It support

webfansplz 413 Dec 30, 2022
Basic https setup using an automatically generated self-signed certificate

@vitejs/plugin-basic-ssl A plugin to generate untrusted certificates which still allows to access the page after proceeding a wall with warning. In mo

vite 81 Jan 2, 2023
🐝 A vite plugin automatically export files & HMR support

vite-plugin-hot-export Automatically export files with HMR English|简体中文 Why ? When developing, we often need to download some images or svg from the i

Frozen FIsh 54 Nov 12, 2022
Easily connect your Nuxt3 application to your directus server. 🐰

nuxt-directus Directus Module for Nuxt 3 ✨ Release Notes ?? Read the documentation Features Nuxt3 ready Handle authentication RESTful methods TypeScri

Conner 109 Dec 28, 2022
:necktie: :briefcase: Build fast :rocket: and easy multiple beautiful resumes and create your best CV ever! Made with Vue and LESS.

best-resume-ever ?? ?? Build fast ?? and easy multiple beautiful resumes and create your best CV ever! Made with Vue and LESS. Cool Creative Green Pur

Sara Steiert 15.8k Jan 9, 2023
Matteo Bruni 4.7k Jan 4, 2023
The first truly composable CSS animation library. Built for Vue, React, SCSS, and CSS, AnimXYZ will bring your website to life.

AnimXYZ animxyz.com AnimXYZ helps you create, customize, and compose animations for your website. Powered by CSS variables to allow a nearly limitless

Ingram Projects 2.1k Jan 2, 2023
A simple, customization star rating component for your vue3 projects

vue3-star-ratings A simple, customizable component for star ratings Documentation Features Uses svg for the stars, so it can scale without quality los

Abiodun Olunu 14 Oct 7, 2022
Backs up your favourite and recently used gifs/emotes and restores them in case discord clears them after logouts or for other reasons

Persist Favourites This plugin solves the problem of Discord randomly deciding to clear your gifs or emotes by backing both up regularely and restorin

Vens Powercord Plugins 18 Oct 13, 2022
quickly start your Vue dev server

vue-fast-dev-server 10倍缩短您的vue dev server启动时间 安装 npm install vue-fast-dev-server --save-dev vue.config.js const path = require('path') module.exports

null 22 Feb 28, 2022
OSI helps you to track your all open-source Internships and Program in a single place ⚡

Open Source Internships Overview ?? Dark Theme Light Theme Run locally ?? Fork this repo. open-source-internships ?? Clone the repo. ⏬ git clone https

Rohan kumar 39 Jan 2, 2023
Add linked data to the YAML of your Obsidian notes.

Obsidian Linked Data Vocabularies Plugin This plugin adds YAML keys for the selected heading, url (optional), and broader, narrower and related headin

null 53 Oct 13, 2022
Some compile-time magic for your Vite project

?? You can help the author become a full-time open-source maintainer by sponsoring him on GitHub. vite-plugin-compile-time Use this plugin to generate

EGOIST 90 Dec 15, 2022