@testing-library/svelte 1.0.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2019 Ben Monro <ben.monro@gmail.com> (https://github.com/benmonro)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,259 @@
1
+ <div align="center">
2
+ <h1>Svelte Testing Library</h1>
3
+
4
+ <a href="https://www.emojione.com/emoji/1f410">
5
+ <img
6
+ height="80"
7
+ width="80"
8
+ alt="chipmunk"
9
+ src="https://raw.githubusercontent.com/testing-library/svelte-testing-library/main/other/chipmunk.png"
10
+ />
11
+ </a>
12
+
13
+ <p>Simple and complete Svelte testing utilities that encourage good testing practices.</p>
14
+
15
+ [**Read The Docs**][stl-docs] | [Edit the docs][stl-docs-repo] | [Examples](./examples)
16
+
17
+ <!-- prettier-ignore-start -->
18
+
19
+ [![Build Status][build-badge]][build]
20
+ [![Code Coverage][coverage-badge]][coverage]
21
+ [![version][version-badge]][package]
22
+ [![downloads][downloads-badge]][downloads]
23
+ [![MIT License][license-badge]][license]
24
+
25
+ [![All Contributors][contributors-badge]][contributors]
26
+ [![PRs Welcome][prs-badge]][prs]
27
+ [![Code of Conduct][coc-badge]][coc]
28
+ [![Discord][discord-badge]][discord]
29
+
30
+ [![Watch on GitHub][github-watch-badge]][github-watch]
31
+ [![Star on GitHub][github-star-badge]][github-star]
32
+ [![Tweet][twitter-badge]][twitter]
33
+
34
+ <!-- prettier-ignore-end -->
35
+
36
+ </div>
37
+
38
+ <hr />
39
+
40
+ [stl-docs]: https://testing-library.com/docs/svelte-testing-library/intro
41
+ [stl-docs-repo]: https://github.com/testing-library/testing-library-docs
42
+ [build-badge]: https://img.shields.io/github/actions/workflow/status/testing-library/svelte-testing-library/release.yml?style=flat-square
43
+ [build]: https://github.com/testing-library/svelte-testing-library/actions
44
+ [coverage-badge]: https://img.shields.io/codecov/c/github/testing-library/svelte-testing-library.svg?style=flat-square
45
+ [coverage]: https://codecov.io/github/testing-library/svelte-testing-library
46
+ [version-badge]: https://img.shields.io/npm/v/@testing-library/svelte.svg?style=flat-square
47
+ [package]: https://www.npmjs.com/package/@testing-library/svelte
48
+ [downloads-badge]: https://img.shields.io/npm/dm/@testing-library/svelte.svg?style=flat-square
49
+ [downloads]: http://www.npmtrends.com/@testing-library/svelte
50
+ [license-badge]: https://img.shields.io/github/license/testing-library/svelte-testing-library?color=b&style=flat-square
51
+ [license]: https://github.com/testing-library/svelte-testing-library/blob/main/LICENSE
52
+ [contributors-badge]: https://img.shields.io/badge/all_contributors-8-orange.svg?style=flat-square
53
+ [contributors]: #contributors
54
+ [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square
55
+ [prs]: http://makeapullrequest.com
56
+ [coc-badge]: https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square
57
+ [coc]: https://github.com/testing-library/svelte-testing-library/blob/main/CODE_OF_CONDUCT.md
58
+ [discord-badge]: https://img.shields.io/discord/723559267868737556.svg?color=7389D8&labelColor=6A7EC2&logo=discord&logoColor=ffffff&style=flat-square
59
+ [discord]: https://discord.gg/testing-library
60
+ [github-watch-badge]: https://img.shields.io/github/watchers/testing-library/svelte-testing-library.svg?style=social
61
+ [github-watch]: https://github.com/testing-library/svelte-testing-library/watchers
62
+ [github-star-badge]: https://img.shields.io/github/stars/testing-library/svelte-testing-library.svg?style=social
63
+ [github-star]: https://github.com/testing-library/svelte-testing-library/stargazers
64
+ [twitter]: https://twitter.com/intent/tweet?text=Check%20out%20svelte-testing-library%20by%20%40@TestingLib%20https%3A%2F%2Fgithub.com%2Ftesting-library%2Fsvelte-testing-library%20%F0%9F%91%8D
65
+ [twitter-badge]: https://img.shields.io/twitter/url/https/github.com/testing-library/svelte-testing-library.svg?style=social
66
+
67
+ ## Table of Contents
68
+
69
+ - [The Problem](#the-problem)
70
+ - [This Solution](#this-solution)
71
+ - [Installation](#installation)
72
+ - [Setup](#setup)
73
+ - [Auto-cleanup](#auto-cleanup)
74
+ - [Docs](#docs)
75
+ - [Issues](#issues)
76
+ - [🐛 Bugs](#-bugs)
77
+ - [💡 Feature Requests](#-feature-requests)
78
+ - [❓ Questions](#-questions)
79
+ - [Contributors](#contributors)
80
+
81
+ ## The Problem
82
+
83
+ You want to write maintainable tests for your [Svelte][svelte] components.
84
+
85
+ [svelte]: https://svelte.dev/
86
+
87
+ ## This Solution
88
+
89
+ `@testing-library/svelte` is a lightweight library for testing Svelte
90
+ components. It provides functions on top of `svelte` and
91
+ `@testing-library/dom` so you can mount Svelte components and query their
92
+ rendered output in the DOM. Its primary guiding principle is:
93
+
94
+ > [The more your tests resemble the way your software is used, the more
95
+ > confidence they can give you.][guiding-principle]
96
+
97
+ [guiding-principle]: https://twitter.com/kentcdodds/status/977018512689455106
98
+
99
+ ## Installation
100
+
101
+ This module is distributed via [npm][npm] which is bundled with [node][node] and
102
+ should be installed as one of your project's `devDependencies`:
103
+
104
+ ```shell
105
+ npm install --save-dev @testing-library/svelte
106
+ ```
107
+
108
+ This library supports `svelte` versions `3`, `4`, and `5`.
109
+
110
+ You may also be interested in installing `@testing-library/jest-dom` so you can
111
+ use [the custom jest matchers][jest-dom].
112
+
113
+ [npm]: https://www.npmjs.com/
114
+ [node]: https://nodejs.org
115
+ [jest-dom]: https://github.com/testing-library/jest-dom
116
+
117
+ ## Setup
118
+
119
+ We recommend using `@testing-library/svelte` with [Vitest][] as your test
120
+ runner. To get started, add the `svelteTesting` plugin to your Vite or Vitest
121
+ config.
122
+
123
+ ```diff
124
+ // vite.config.js
125
+ import { svelte } from '@sveltejs/vite-plugin-svelte'
126
+ + import { svelteTesting } from '@testing-library/svelte/vite'
127
+
128
+ export default defineConfig({
129
+ plugins: [
130
+ svelte(),
131
+ + svelteTesting(),
132
+ ]
133
+ });
134
+ ```
135
+
136
+ See the [setup docs][] for more detailed setup instructions, including for other
137
+ test runners like Jest.
138
+
139
+ [vitest]: https://vitest.dev/
140
+ [setup docs]: https://testing-library.com/docs/svelte-testing-library/setup
141
+
142
+ ### Auto-cleanup
143
+
144
+ In Vitest (via the `svelteTesting` plugin) and Jest (via the `beforeEach` and `afterEach` globals),
145
+ this library will automatically setup and cleanup the test environment before and after each test.
146
+
147
+ To do your own cleanup, or if you're using another framework, call the `setup` and `cleanup` functions yourself:
148
+
149
+ ```js
150
+ import { cleanup, render, setup } from '@testing-library/svelte'
151
+
152
+ // before
153
+ setup()
154
+
155
+ // test
156
+ render(/* ... */)
157
+
158
+ // after
159
+ cleanup()
160
+ ```
161
+
162
+ To disable auto-cleanup in Vitest, set the `autoCleanup` option of the plugin to false:
163
+
164
+ ```js
165
+ svelteTesting({ autoCleanup: false })
166
+ ```
167
+
168
+ To disable auto-cleanup in Jest and other frameworks with global test hooks,
169
+ set the `STL_SKIP_AUTO_CLEANUP` environment variable:
170
+
171
+ ```shell
172
+ STL_SKIP_AUTO_CLEANUP=1 jest
173
+ ```
174
+
175
+ ## Docs
176
+
177
+ See the [**docs**][stl-docs] over at the Testing Library website.
178
+
179
+ ## Issues
180
+
181
+ _Looking to contribute? Look for the [Good First Issue][good-first-issue]
182
+ label._
183
+
184
+ [good-first-issue]: https://github.com/testing-library/svelte-testing-library/issues?utf8=✓&q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3A"good+first+issue"+
185
+
186
+ ### 🐛 Bugs
187
+
188
+ Please file an issue for bugs, missing documentation, or unexpected behavior.
189
+
190
+ [**See Bugs**][bugs]
191
+
192
+ [bugs]: https://github.com/testing-library/svelte-testing-library/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Acreated-desc
193
+
194
+ ### 💡 Feature Requests
195
+
196
+ Please file an issue to suggest new features. Vote on feature requests by adding
197
+ a 👍. This helps maintainers prioritize what to work on.
198
+
199
+ [**See Feature Requests**][requests]
200
+
201
+ [requests]: https://github.com/testing-library/svelte-testing-library/issues?q=is%3Aissue+sort%3Areactions-%2B1-desc+label%3Aenhancement+is%3Aopen
202
+
203
+ ### ❓ Questions
204
+
205
+ For questions related to using the library, please visit a support community
206
+ instead of filing an issue on GitHub.
207
+
208
+ - [Discord][discord]
209
+ - [Stack Overflow][stackoverflow]
210
+
211
+ [stackoverflow]: https://stackoverflow.com/questions/tagged/svelte-testing-library
212
+
213
+ ## Contributors
214
+
215
+ Thanks goes to these people ([emoji key][emojis]):
216
+
217
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
218
+
219
+ <!-- prettier-ignore-start -->
220
+
221
+ <!-- markdownlint-disable -->
222
+
223
+ <table>
224
+ <tbody>
225
+ <tr>
226
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/benmonro"><img src="https://avatars3.githubusercontent.com/u/399236?v=4?s=100" width="100px;" alt="Ben Monro"/><br /><sub><b>Ben Monro</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=benmonro" title="Code">💻</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=benmonro" title="Tests">⚠️</a> <a href="#ideas-benmonro" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=benmonro" title="Documentation">📖</a></td>
227
+ <td align="center" valign="top" width="14.28%"><a href="https://twitter.com/EmilTholin"><img src="https://avatars0.githubusercontent.com/u/11573167?v=4?s=100" width="100px;" alt="Emil Tholin"/><br /><sub><b>Emil Tholin</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=EmilTholin" title="Code">💻</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=EmilTholin" title="Tests">⚠️</a> <a href="#ideas-EmilTholin" title="Ideas, Planning, & Feedback">🤔</a></td>
228
+ <td align="center" valign="top" width="14.28%"><a href="https://medium.com/@oieduardorabelo"><img src="https://avatars1.githubusercontent.com/u/829902?v=4?s=100" width="100px;" alt="Eduardo Rabelo"/><br /><sub><b>Eduardo Rabelo</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=oieduardorabelo" title="Tests">⚠️</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=oieduardorabelo" title="Code">💻</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=oieduardorabelo" title="Documentation">📖</a> <a href="#example-oieduardorabelo" title="Examples">💡</a></td>
229
+ <td align="center" valign="top" width="14.28%"><a href="http://timdeschryver.dev"><img src="https://avatars1.githubusercontent.com/u/28659384?v=4?s=100" width="100px;" alt="Tim Deschryver"/><br /><sub><b>Tim Deschryver</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=timdeschryver" title="Documentation">📖</a></td>
230
+ <td align="center" valign="top" width="14.28%"><a href="http://www.ematipico.com"><img src="https://avatars3.githubusercontent.com/u/602478?v=4?s=100" width="100px;" alt="Emanuele"/><br /><sub><b>Emanuele</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=ematipico" title="Code">💻</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=ematipico" title="Tests">⚠️</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=ematipico" title="Documentation">📖</a></td>
231
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/pngwn"><img src="https://avatars1.githubusercontent.com/u/12937446?v=4?s=100" width="100px;" alt="pngwn"/><br /><sub><b>pngwn</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=pngwn" title="Code">💻</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=pngwn" title="Tests">⚠️</a></td>
232
+ <td align="center" valign="top" width="14.28%"><a href="https://twitter.com/sebsilbermann"><img src="https://avatars3.githubusercontent.com/u/12292047?v=4?s=100" width="100px;" alt="Sebastian Silbermann"/><br /><sub><b>Sebastian Silbermann</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=eps1lon" title="Code">💻</a></td>
233
+ </tr>
234
+ <tr>
235
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/mihar-22"><img src="https://avatars3.githubusercontent.com/u/14304599?s=460&v=4?s=100" width="100px;" alt="Rahim Alwer"/><br /><sub><b>Rahim Alwer</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=mihar-22" title="Code">💻</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=mihar-22" title="Documentation">📖</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=mihar-22" title="Tests">⚠️</a> <a href="https://github.com/testing-library/svelte-testing-library/pulls?q=is%3Apr+reviewed-by%3Amihar-22" title="Reviewed Pull Requests">👀</a></td>
236
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/MirrorBytes"><img src="https://avatars3.githubusercontent.com/u/22119469?v=4?s=100" width="100px;" alt="Bob"/><br /><sub><b>Bob</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/issues?q=author%3AMirrorBytes" title="Bug reports">🐛</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=MirrorBytes" title="Code">💻</a></td>
237
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/ronmerkin"><img src="https://avatars.githubusercontent.com/u/17492527?v=4?s=100" width="100px;" alt="Ron Merkin"/><br /><sub><b>Ron Merkin</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=ronmerkin" title="Code">💻</a></td>
238
+ <td align="center" valign="top" width="14.28%"><a href="http://www.benmccann.com"><img src="https://avatars.githubusercontent.com/u/322311?v=4?s=100" width="100px;" alt="Ben McCann"/><br /><sub><b>Ben McCann</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=benmccann" title="Tests">⚠️</a></td>
239
+ <td align="center" valign="top" width="14.28%"><a href="https://johnbowser.dev/"><img src="https://avatars.githubusercontent.com/u/66637570?v=4?s=100" width="100px;" alt="John Bowser"/><br /><sub><b>John Bowser</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=jgbowser" title="Code">💻</a> <a href="https://github.com/testing-library/svelte-testing-library/commits?author=jgbowser" title="Tests">⚠️</a></td>
240
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/ysitbon"><img src="https://avatars.githubusercontent.com/u/1370679?v=4?s=100" width="100px;" alt="Yoann"/><br /><sub><b>Yoann</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=ysitbon" title="Code">💻</a></td>
241
+ <td align="center" valign="top" width="14.28%"><a href="https://techblog.babyl.ca/"><img src="https://avatars.githubusercontent.com/u/19954?v=4?s=100" width="100px;" alt="Yanick Champoux"/><br /><sub><b>Yanick Champoux</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=yanick" title="Code">💻</a></td>
242
+ </tr>
243
+ <tr>
244
+ <td align="center" valign="top" width="14.28%"><a href="https://michael.cousins.io/"><img src="https://avatars.githubusercontent.com/u/2963448?v=4?s=100" width="100px;" alt="Michael Cousins"/><br /><sub><b>Michael Cousins</b></sub></a><br /><a href="https://github.com/testing-library/svelte-testing-library/commits?author=mcous" title="Code">💻</a></td>
245
+ </tr>
246
+ </tbody>
247
+ </table>
248
+
249
+ <!-- markdownlint-restore -->
250
+
251
+ <!-- prettier-ignore-end -->
252
+
253
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
254
+
255
+ This project follows the [all-contributors][all-contributors] specification.
256
+ Contributions of any kind welcome!
257
+
258
+ [emojis]: https://github.com/all-contributors/all-contributors#emoji-key
259
+ [all-contributors]: https://github.com/all-contributors/all-contributors
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@testing-library/svelte",
3
+ "version": "1.0.0-next.1",
4
+ "description": "Simple and complete Svelte testing utilities that encourage good testing practices.",
5
+ "main": "src/index.js",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "default": "./src/index.js"
10
+ },
11
+ "./svelte5": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./src/index.js"
14
+ },
15
+ "./vitest": {
16
+ "types": "./dist/vitest.d.ts",
17
+ "default": "./src/vitest.js"
18
+ },
19
+ "./vite": {
20
+ "types": "./dist/vite.d.ts",
21
+ "default": "./src/vite.js"
22
+ }
23
+ },
24
+ "type": "module",
25
+ "types": "dist/index.d.ts",
26
+ "license": "MIT",
27
+ "homepage": "https://github.com/testing-library/svelte-testing-library#readme",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/testing-library/svelte-testing-library.git",
31
+ "directory": "packages/svelte"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/testing-library/svelte-testing-library/issues"
35
+ },
36
+ "engines": {
37
+ "node": ">= 10"
38
+ },
39
+ "keywords": [
40
+ "testing",
41
+ "svelte",
42
+ "ui",
43
+ "dom",
44
+ "jsdom",
45
+ "unit",
46
+ "integration",
47
+ "functional",
48
+ "end-to-end",
49
+ "e2e"
50
+ ],
51
+ "files": [
52
+ "src",
53
+ "dist"
54
+ ],
55
+ "peerDependencies": {
56
+ "svelte": "^3 || ^4 || ^5 || ^5.0.0-next.0",
57
+ "vite": "*",
58
+ "vitest": "*"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "vite": {
62
+ "optional": true
63
+ },
64
+ "vitest": {
65
+ "optional": true
66
+ }
67
+ },
68
+ "dependencies": {
69
+ "@testing-library/dom": "9.x.x || 10.x.x",
70
+ "@testing-library/svelte-core": "1.0.0-next.1"
71
+ },
72
+ "publishConfig": {
73
+ "access": "public",
74
+ "provenance": true
75
+ }
76
+ }
package/src/index.js ADDED
@@ -0,0 +1,33 @@
1
+ import { act, cleanup, setup } from './pure.js'
2
+
3
+ // If we're running in a test runner that supports beforeEach/afterEach
4
+ // we'll automatically run setup and cleanup before and after each test
5
+ // this ensures that tests run in isolation from each other
6
+ // if you don't like this then set the STL_SKIP_AUTO_CLEANUP env variable.
7
+ if (typeof process !== 'undefined' && !process.env.STL_SKIP_AUTO_CLEANUP) {
8
+ if (typeof beforeEach === 'function') {
9
+ beforeEach(() => {
10
+ setup()
11
+ })
12
+ }
13
+
14
+ if (typeof afterEach === 'function') {
15
+ afterEach(async () => {
16
+ await act()
17
+ cleanup()
18
+ })
19
+ }
20
+ }
21
+
22
+ // export all base queries, screen, etc.
23
+ export * from '@testing-library/dom'
24
+
25
+ // export svelte-specific functions and custom `fireEvent`
26
+ export {
27
+ act,
28
+ cleanup,
29
+ fireEvent,
30
+ render,
31
+ setup,
32
+ UnknownSvelteOptionsError,
33
+ } from './pure.js'
package/src/pure.js ADDED
@@ -0,0 +1,141 @@
1
+ import {
2
+ configure as configureDTL,
3
+ fireEvent as baseFireEvent,
4
+ getConfig as getDTLConfig,
5
+ getQueriesForElement,
6
+ prettyDOM,
7
+ } from '@testing-library/dom'
8
+ import * as Core from '@testing-library/svelte-core'
9
+ import * as Svelte from 'svelte'
10
+
11
+ /**
12
+ * Customize how Svelte renders the component.
13
+ *
14
+ * @template {import('@testing-library/svelte-core/types').Component} C
15
+ * @typedef {import('@testing-library/svelte-core/types').ComponentOptions<C>} SvelteComponentOptions
16
+ */
17
+
18
+ /**
19
+ * Customize how Testing Library sets up the document and binds queries.
20
+ *
21
+ * @template {import('@testing-library/dom').Queries} [Q=typeof import('@testing-library/dom').queries]
22
+ * @typedef {{
23
+ * baseElement?: HTMLElement
24
+ * queries?: Q
25
+ * }} RenderOptions
26
+ */
27
+
28
+ /**
29
+ * The rendered component and bound testing functions.
30
+ *
31
+ * @template {import('@testing-library/svelte-core/types').Component} C
32
+ * @template {import('@testing-library/dom').Queries} [Q=typeof import('@testing-library/dom').queries]
33
+ *
34
+ * @typedef {{
35
+ * container: HTMLElement
36
+ * baseElement: HTMLElement
37
+ * component: import('@testing-library/svelte-core/types').Exports<C>
38
+ * debug: (el?: HTMLElement | DocumentFragment) => void
39
+ * rerender: import('@testing-library/svelte-core/types').Rerender<C>
40
+ * unmount: () => void
41
+ * } & {
42
+ * [P in keyof Q]: import('@testing-library/dom').BoundFunction<Q[P]>
43
+ * }} RenderResult
44
+ */
45
+
46
+ /**
47
+ * Render a component into the document.
48
+ *
49
+ * @template {import('@testing-library/svelte-core/types').Component} C
50
+ * @template {import('@testing-library/dom').Queries} [Q=typeof import('@testing-library/dom').queries]
51
+ *
52
+ * @param {import('@testing-library/svelte-core/types').ComponentImport<C>} Component - The component to render.
53
+ * @param {SvelteComponentOptions<C>} options - Customize how Svelte renders the component.
54
+ * @param {RenderOptions<Q>} renderOptions - Customize how Testing Library sets up the document and binds queries.
55
+ * @returns {RenderResult<C, Q>} The rendered component and bound testing functions.
56
+ */
57
+ const render = (Component, options = {}, renderOptions = {}) => {
58
+ const { baseElement, container, component, unmount, rerender } = Core.render(
59
+ Component,
60
+ options,
61
+ renderOptions
62
+ )
63
+
64
+ return {
65
+ baseElement,
66
+ container,
67
+ component,
68
+ rerender,
69
+ unmount,
70
+ debug: (el = baseElement) => console.log(prettyDOM(el)),
71
+ ...getQueriesForElement(baseElement, renderOptions.queries),
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Configure `@testing-library/dom` for usage with Svelte.
77
+ *
78
+ * Ensures events fired from `@testing-library/dom`
79
+ * and `@testing-library/user-event` wait for Svelte
80
+ * to flush changes to the DOM before proceeding.
81
+ */
82
+ const setup = () => {
83
+ const originalDTLConfig = getDTLConfig()
84
+
85
+ configureDTL({
86
+ asyncWrapper: act,
87
+ eventWrapper: Svelte.flushSync ?? ((cb) => cb()),
88
+ })
89
+
90
+ Core.addCleanupTask(() => {
91
+ configureDTL(originalDTLConfig)
92
+ })
93
+ }
94
+
95
+ /** Unmount components, remove elements added to `<body>`, and reset `@testing-library/dom`. */
96
+ const cleanup = () => {
97
+ Core.cleanup()
98
+ }
99
+
100
+ /**
101
+ * Call a function and wait for Svelte to flush pending changes.
102
+ *
103
+ * @template T
104
+ * @param {(() => Promise<T>) | () => T} [fn] - A function, which may be `async`, to call before flushing updates.
105
+ * @returns {Promise<T>}
106
+ */
107
+ const act = async (fn) => {
108
+ let result
109
+ if (fn) {
110
+ result = await fn()
111
+ }
112
+ await Svelte.tick()
113
+ return result
114
+ }
115
+
116
+ /**
117
+ * @typedef {(...args: Parameters<import('@testing-library/dom').FireFunction>) => Promise<ReturnType<import('@testing-library/dom').FireFunction>>} FireFunction
118
+ */
119
+
120
+ /**
121
+ * @typedef {{
122
+ * [K in import('@testing-library/dom').EventType]: (...args: Parameters<import('@testing-library/dom').FireObject[K]>) => Promise<ReturnType<import('@testing-library/dom').FireObject[K]>>
123
+ * }} FireObject
124
+ */
125
+
126
+ /**
127
+ * Fire an event on an element.
128
+ *
129
+ * Consider using `@testing-library/user-event` instead, if possible.
130
+ * @see https://testing-library.com/docs/user-event/intro/
131
+ *
132
+ * @type {FireFunction & FireObject}
133
+ */
134
+ const fireEvent = async (...args) => act(() => baseFireEvent(...args))
135
+
136
+ for (const [key, baseEvent] of Object.entries(baseFireEvent)) {
137
+ fireEvent[key] = async (...args) => act(() => baseEvent(...args))
138
+ }
139
+
140
+ export { UnknownSvelteOptionsError } from '@testing-library/svelte-core'
141
+ export { act, cleanup, fireEvent, render, setup }
package/src/vite.js ADDED
@@ -0,0 +1,133 @@
1
+ import path from 'node:path'
2
+ import url from 'node:url'
3
+
4
+ const STL_PACKAGES = ['@testing-library/svelte', '@testing-library/svelte-core']
5
+
6
+ /**
7
+ * Vite plugin to configure @testing-library/svelte.
8
+ *
9
+ * Ensures Svelte is imported correctly in tests
10
+ * and that the DOM is cleaned up after each test.
11
+ *
12
+ * @param {{resolveBrowser?: boolean, autoCleanup?: boolean, noExternal?: boolean}} options
13
+ * @returns {import('vite').Plugin}
14
+ */
15
+ export const svelteTesting = ({
16
+ resolveBrowser = true,
17
+ autoCleanup = true,
18
+ noExternal = true,
19
+ } = {}) => ({
20
+ name: 'vite-plugin-svelte-testing-library',
21
+ config: (config) => {
22
+ if (!process.env.VITEST) {
23
+ return
24
+ }
25
+
26
+ if (resolveBrowser) {
27
+ addBrowserCondition(config)
28
+ }
29
+
30
+ if (autoCleanup) {
31
+ addAutoCleanup(config)
32
+ }
33
+
34
+ if (noExternal) {
35
+ addNoExternal(config)
36
+ }
37
+ },
38
+ })
39
+
40
+ /**
41
+ * Add `browser` to `resolve.conditions` before `node`.
42
+ *
43
+ * This ensures that Svelte's browser code is used in tests,
44
+ * rather than its SSR code.
45
+ *
46
+ * @param {import('vitest/config').UserConfig} config
47
+ */
48
+ const addBrowserCondition = (config) => {
49
+ const resolve = config.resolve ?? {}
50
+ const conditions = resolve.conditions ?? []
51
+ const nodeConditionIndex = conditions.indexOf('node')
52
+ const browserConditionIndex = conditions.indexOf('browser')
53
+
54
+ if (
55
+ nodeConditionIndex !== -1 &&
56
+ (nodeConditionIndex < browserConditionIndex || browserConditionIndex === -1)
57
+ ) {
58
+ conditions.splice(nodeConditionIndex, 0, 'browser')
59
+ }
60
+
61
+ resolve.conditions = conditions
62
+ config.resolve = resolve
63
+ }
64
+
65
+ /**
66
+ * Add auto-cleanup file to Vitest's setup files.
67
+ *
68
+ * @param {import('vitest/config').UserConfig} config
69
+ */
70
+ const addAutoCleanup = (config) => {
71
+ const test = config.test ?? {}
72
+ let setupFiles = test.setupFiles ?? []
73
+
74
+ if (test.globals) {
75
+ return
76
+ }
77
+
78
+ if (typeof setupFiles === 'string') {
79
+ setupFiles = [setupFiles]
80
+ }
81
+
82
+ setupFiles.push(
83
+ path.join(path.dirname(url.fileURLToPath(import.meta.url)), './vitest.js')
84
+ )
85
+
86
+ test.setupFiles = setupFiles
87
+ config.test = test
88
+ }
89
+
90
+ /**
91
+ * Add `@testing-library/svelte` to Vite's noExternal rules, if not present.
92
+ *
93
+ * This ensures `@testing-library/svelte` is processed by `@sveltejs/vite-plugin-svelte`
94
+ * in certain monorepo setups.
95
+ */
96
+ const addNoExternal = (config) => {
97
+ const ssr = config.ssr ?? {}
98
+ let noExternal = ssr.noExternal ?? []
99
+
100
+ if (noExternal === true) {
101
+ return
102
+ }
103
+
104
+ if (typeof noExternal === 'string' || noExternal instanceof RegExp) {
105
+ noExternal = [noExternal]
106
+ }
107
+
108
+ if (!Array.isArray(noExternal)) {
109
+ return
110
+ }
111
+
112
+ const missingPackages = []
113
+
114
+ for (const packageName of STL_PACKAGES) {
115
+ const isIncluded = noExternal.some(
116
+ (rule) =>
117
+ (typeof rule === 'string' && rule === packageName) ||
118
+ (rule instanceof RegExp && rule.test(packageName))
119
+ )
120
+
121
+ if (!isIncluded) {
122
+ missingPackages.push(packageName)
123
+ }
124
+ }
125
+
126
+ if (missingPackages.length === 0) {
127
+ return
128
+ }
129
+
130
+ noExternal.push(...missingPackages)
131
+ ssr.noExternal = noExternal
132
+ config.ssr = ssr
133
+ }
package/src/vitest.js ADDED
@@ -0,0 +1,11 @@
1
+ import { act, cleanup, setup } from '@testing-library/svelte'
2
+ import { beforeEach } from 'vitest'
3
+
4
+ beforeEach(() => {
5
+ setup()
6
+
7
+ return async () => {
8
+ await act()
9
+ cleanup()
10
+ }
11
+ })