Skip to content

Commit

Permalink
fix(vitest): add types for the new global jsdom variable (#5164)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Feb 9, 2024
1 parent 3afe68f commit 0f898d8
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
10 changes: 9 additions & 1 deletion docs/config/index.md
Expand Up @@ -512,7 +512,15 @@ export default <Environment>{
Vitest also exposes `builtinEnvironments` through `vitest/environments` entry, in case you just want to extend it. You can read more about extending environments in [our guide](/guide/environment).

::: tip
Since Vitest 1.3.0 jsdom environment exposes `jsdom` global variable equal to the current [JSDOM](https://github.com/jsdom/jsdom) instance.
Since Vitest 1.3.0 jsdom environment exposes `jsdom` global variable equal to the current [JSDOM](https://github.com/jsdom/jsdom) instance. If you want TypeScript to recognize it, you can add `vitest/jsdom` to your `tsconfig.json` when you use this environment:

```json
{
"compilerOptions": {
"types": ["vitest/jsdom"]
}
}
```
:::

### environmentOptions
Expand Down
6 changes: 6 additions & 0 deletions packages/vitest/jsdom.d.ts
@@ -0,0 +1,6 @@
import type { JSDOM } from 'jsdom'

declare global {
const jsdom: JSDOM
}
export {}
3 changes: 3 additions & 0 deletions packages/vitest/package.json
Expand Up @@ -38,6 +38,9 @@
"./globals": {
"types": "./globals.d.ts"
},
"./jsdom": {
"types": "./jsdom.d.ts"
},
"./importMeta": {
"types": "./importMeta.d.ts"
},
Expand Down
8 changes: 8 additions & 0 deletions test/core/test/environments/jsdom.spec.ts
Expand Up @@ -105,3 +105,11 @@ test('request doesn\'t support absolute URL because jsdom doesn\'t provide compa
const _r = new Request('/api', { method: 'GET' })
}).toThrow(/Failed to parse URL/)
})

test('jsdom global is exposed', () => {
// @ts-expect-error -- jsdom is not exposed in our types because we use a single tsconfig for all
const dom = jsdom
expect(dom).toBeDefined()
dom.reconfigure({ url: 'https://examples.new.com' })
expect(location.href).toBe('https://examples.new.com/')
})

0 comments on commit 0f898d8

Please sign in to comment.