Coder Social home page Coder Social logo

nickbreaton / vitest-svelte-kit Goto Github PK

View Code? Open in Web Editor NEW
44.0 2.0 4.0 649 KB

[Deprecated] Automatically configure Vitest from your SvelteKit configuration.

Home Page: https://npm.im/vitest-svelte-kit

License: MIT License

JavaScript 67.04% HTML 2.73% Svelte 4.22% TypeScript 26.01%
vite svelte sveltekit

vitest-svelte-kit's Introduction

vitest-svelte-kit

Automatically configure Vitest from your SvelteKit configuration.

Deprecation Notice ⚠️

This package is no longer necessary nor maintained given that SvelteKit is now exposed as a Vite plugin. To learn more about how to configure Vite – and subsequently Vitest – in SvelteKit, see here.

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 Included

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

vitest-svelte-kit's People

Contributors

benmccann avatar nickbreaton avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vitest-svelte-kit's Issues

This page isn’t working

run: npm run dev have error on sveltekit page

This page isn’t workinglocalhost is currently unable to handle this request. HTTP ERROR 500

web browser console.log
(index):6774 crbug/1173575, non-JS module files deprecated.

remove files vite.config.js all fix and working page..

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!

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 ?

Not able to install due to "vitest-svelte-kit": "workspace:*"

I download the example, then run pnpm i returns an error.

 ERR_PNPM_NO_MATCHING_VERSION_INSIDE_WORKSPACE  In : No matching version found for vitest-svelte-kit@* inside the workspace

Solution

You need to remove "vitest-svelte-kit": "workspace:*" from package.json.

Then you need to install:

pnpm i -D vitest vitest-svelte-kit

Recursion in test script

I tried to run npm run test to see if all the tests works to fix #11, but they recursively call the test script and never run

[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;

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

Node module dependencies error for simple Form Svelte component (Sveltekit App)

I was able to configure vitest-svelte-kit exactly as mentioned in the docs and the example for sveltekit provided but facing and issue when there are 3rdParty dependencies from another svelte lib

There are two issue

  • (Minor) VS Code - IDE also shows "Module Not Found" for all svelte imports in the test file . This is minor as the other tests work

  • (Main Issue) - Get an error if the svelte component I am testing is futher importing other svelte components (in my case felte)

  • Any guidance to solve this will be a great help !!

  • Error

 ❯ src/lib/forms/ConfirmDeleteForm.test.ts (0)
 √ src/lib/about/Hero.test.ts (1)
 √ src/routes/about/about.test.ts (2)

⎯⎯⎯⎯ Failed Suites 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL  src/lib/forms/ConfirmDeleteForm.test.ts [ src/lib/forms/ConfirmDeleteForm.test.ts ]
Error: Cannot find module 'xxxx\node_modules\@felte\reporter-svelte\src\reporter' imported from xxx\node_modules\@felte\reporter-svelte\src\index.js
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
  • ConfirmDeleteForm.svelte
<script lang="ts">
	import { onDestroy } from 'svelte';
	import { createForm } from 'felte';
	import { reporter } from '@felte/reporter-svelte';
...
</script>

{#if isOpen}
	<div
		role="dialog"
		class="fixed inset-0 flex items-center justify-center pointer-events-none z-[99999]"
	>
		<form
			use:form
			class="flex flex-col gap-2 p-2 items-center justify-center text-xs bg-white w-80 pointer-events-auto rounded"
		>
			<fieldset class="flex flex-col w-full p-2">
				<legend class="text-sm font-bold text-center">{title}</legend>
			</fieldset>
			<div class="flex items-center gap-2 justify-end w-full p-2">
			...
			</div>
		</form>
	</div>
{/if}
  • ConfirmDeleteForm.test.ts
/**
 * @vitest-environment jsdom
 */

 import { render, screen } from '@testing-library/svelte';
 import { test, expect } from 'vitest';
 import ConfirmDeleteForm from './ConfirmDeleteForm.svelte';
 
 test('shows proper heading when rendered', () => {
     render(ConfirmDeleteForm,{
         isOpen: true,
         title: "Delete this item?",
     });
     expect(screen.getByText(`Delete this item?`)).toBeTruthy();
 });
 
  • vitest.config.js
import { extractFromSvelteConfig } from "vitest-svelte-kit"

export default extractFromSvelteConfig()
  • tsconfig.json
{
	"extends": "./.svelte-kit/tsconfig.json",
	"compilerOptions": {
		"moduleResolution": "node",
		"module": "es2020",
		"lib": ["es2020", "DOM"],
		"target": "es2019",
		"importsNotUsedAsValues": "error",
		"isolatedModules": true,
		"resolveJsonModule": true,
		"sourceMap": true,
		"esModuleInterop": true,
		"skipLibCheck": true,
		"forceConsistentCasingInFileNames": true,
		"baseUrl": ".",
		"allowJs": true,
		"checkJs": true,
		"paths": {
			"$lib": ["./src/lib"],
			"$lib/*": ["./src/lib/*"]
		},
		"types": ["vitest/importMeta"]
	},
	"include": [
		"src/**/*.d.ts",
		"src/**/*.js",
		"src/**/*.ts",
		"src/**/*.svelte",
		"__tests__/index.spec.ts"
	],
	"exclude": ["src/**/*.spec.ts"]
}

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

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.

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.