Skip to content

Commit

Permalink
Merge branch 'main' into fix/offset-longer-than-source
Browse files Browse the repository at this point in the history
  • Loading branch information
fenghan34 committed Aug 15, 2023
2 parents ed1a531 + a428f8d commit c66a0a2
Show file tree
Hide file tree
Showing 12 changed files with 70 additions and 41 deletions.
2 changes: 1 addition & 1 deletion docs/api/vi.md
Expand Up @@ -82,7 +82,7 @@ import { vi } from 'vitest'

## vi.fn

- **Type:** `(fn?: Function) => CallableMockInstance`
- **Type:** `(fn?: Function) => Mock`

Creates a spy on a function, though can be initiated without one. Every time a function is invoked, it stores its call arguments, returns, and instances. Also, you can manipulate its behavior with [methods](/api/mock).
If no function is given, mock will return `undefined`, when invoked.
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/index.md
Expand Up @@ -109,7 +109,7 @@ export default defineConfig({
Even if you do not use Vite yourself, Vitest relies heavily on it for its transformation pipeline. For that reason, you can also configure any property described in [Vite documentation](https://vitejs.dev/config/).
:::

If you are already using Vite, add `test` property in your Vite config. You'll also need to add a reference to Vitest types using a [triple slash command](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-) at the top of your config file.
If you are already using Vite, add `test` property in your Vite config. You'll also need to add a reference to Vitest types using a [triple slash directive](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-) at the top of your config file.

```ts
/// <reference types="vitest" />
Expand Down
24 changes: 10 additions & 14 deletions docs/guide/migration.md
Expand Up @@ -8,13 +8,13 @@ title: Migration Guide | Guide

Vitest has been designed with a Jest compatible API, in order to make the migration from Jest as simple as possible. Despite those efforts, you may still run into the following differences:

**Globals as a Default**
### Globals as a Default

Jest has their [globals API](https://jestjs.io/docs/api) enabled by default. Vitest does not. You can either enable globals via [the `globals` configuration setting](/config/#globals) or update your code to use imports from the `vitest` module instead.

If you decide to keep globals disabled, be aware that common libraries like [`testing-library`](https://testing-library.com/) will not run auto DOM [cleanup](https://testing-library.com/docs/svelte-testing-library/api/#cleanup).

**Module mocks**
### Module mocks

When mocking a module in Jest, the factory argument's return value is the default export. In Vitest, the factory argument has to return an object with each export explicitly defined. For example, the following `jest.mock` would have to be updated as follows:

Expand All @@ -27,11 +27,11 @@ When mocking a module in Jest, the factory argument's return value is the defaul

For more details please refer to the [`vi.mock` api section](/api/vi#vi-mock).

**Auto-Mocking Behaviour**
### Auto-Mocking Behaviour

Unlike Jest, mocked modules in `<root>/__mocks__` are not loaded unless `vi.mock()` is called. If you need them to be mocked in every test, like in Jest, you can mock them inside [`setupFiles`](/config/#setupfiles).

**Importing the original of a mocked package**
### Importing the original of a mocked package

If you are only partially mocking a package, you might have previously used Jest's function `requireActual`. In Vitest, you should replace these calls with `vi.importActual`.

Expand All @@ -40,17 +40,13 @@ If you are only partially mocking a package, you might have previously used Jest
+ const { cloneDeep } = await vi.importActual('lodash/cloneDeep')
```

**Jasmine API**

Jest exports various [`jasmine`](https://jasmine.github.io/) globals (such as `jasmine.any()`). Any such instances will need to be migrated to [their Vitest counterparts](/api/).

**Envs**
### Envs

Just like Jest, Vitest sets `NODE_ENV` to `test`, if it wasn't set before. Vitest also has a counterpart for `JEST_WORKER_ID` called `VITEST_POOL_ID` (always less than or equal to `maxThreads`), so if you rely on it, don't forget to rename it. Vitest also exposes `VITEST_WORKER_ID` which is a unique ID of a running worker - this number is not affected by `maxThreads`, and will increase with each created worker.

If you want to modify the envs, you will use [replaceProperty API](https://jestjs.io/docs/jest-object#jestreplacepropertyobject-propertykey-value) in Jest, you can use [vi.stubEnv](https://vitest.dev/api/vi.html#vi-stubenv) to do it also in Vitest.

**Done Callback**
### Done Callback

From Vitest v0.10.0, the callback style of declaring tests is deprecated. You can rewrite them to use `async`/`await` functions, or use Promise to mimic the callback style.

Expand All @@ -63,7 +59,7 @@ From Vitest v0.10.0, the callback style of declaring tests is deprecated. You ca
+ }))
```

**Hooks**
### Hooks

`beforeAll`/`beforeEach` hooks may return [teardown function](/api/#setup-and-teardown) in Vitest. Because of that you may need to rewrite your hooks declarations, if they return something other than `undefined` or `null`:

Expand All @@ -72,7 +68,7 @@ From Vitest v0.10.0, the callback style of declaring tests is deprecated. You ca
+ beforeEach(() => { setActivePinia(createTestingPinia()) })
```

**Types**
### Types

Vitest doesn't expose a lot of types on `Vi` namespace, it exists mainly for compatibility with matchers, so you might need to import types directly from `vitest` instead of relying on `Vi` namespace:

Expand All @@ -84,11 +80,11 @@ Vitest doesn't expose a lot of types on `Vi` namespace, it exists mainly for com

Also, Vitest has `Args` type as a first argument instead of `Returns`, as you can see in diff.

**Timers**
### Timers

Vitest doesn't support Jest's legacy timers.

**Vue Snapshots**
### Vue Snapshots

This is not a Jest-specific feature, but if you previously were using Jest with vue-cli preset, you will need to install [`jest-serializer-vue`](https://github.com/eddyerburgh/jest-serializer-vue) package, and use it inside [setupFiles](/config/#setupfiles):

Expand Down
6 changes: 3 additions & 3 deletions packages/ui/client/composables/summary.ts
Expand Up @@ -34,9 +34,9 @@ export const testsTodo = computed(() => testsIgnore.value.filter(f => f.mode ===
export const totalTests = computed(() => testsFailed.value.length + testsSuccess.value.length)
export const time = computed(() => {
const t = getTests(tests.value).reduce((acc, t) => {
if (t.result?.duration)
acc += t.result.duration

acc += Math.max(0, t.collectDuration || 0)
acc += Math.max(0, t.setupDuration || 0)
acc += Math.max(0, t.result?.duration || 0)
return acc
}, 0)

Expand Down
10 changes: 6 additions & 4 deletions packages/vitest/src/node/error.ts
Expand Up @@ -179,10 +179,12 @@ function printModuleWarningForPackage(logger: Logger, path: string, name: string
+ '\n'
+ c.green(`export default {
test: {
deps: {
inline: [
${c.yellow(c.bold(`"${name}"`))}
]
server: {
deps: {
inline: [
${c.yellow(c.bold(`"${name}"`))}
]
}
}
}
}\n`)))
Expand Down
13 changes: 1 addition & 12 deletions packages/vitest/src/node/plugins/ssrReplacer.ts
Expand Up @@ -7,7 +7,7 @@ import { cleanUrl } from 'vite-node/utils'
// import.meta.env.VITE_NAME = 'app' -> process.env.VITE_NAME = 'app'
export function SsrReplacerPlugin(): Plugin {
return {
name: 'vitest:env-replacer',
name: 'vitest:ssr-replacer',
enforce: 'pre',
transform(code, id) {
if (!/\bimport\.meta\.env\b/.test(code) && !/\bimport\.meta\.url\b/.test(code))
Expand All @@ -26,17 +26,6 @@ export function SsrReplacerPlugin(): Plugin {
s.overwrite(startIndex, endIndex, 'process.env')
}

const urls = cleanCode.matchAll(/\bimport\.meta\.url\b/g)

for (const env of urls) {
s ||= new MagicString(code)

const startIndex = env.index!
const endIndex = startIndex + env[0].length

s.overwrite(startIndex, endIndex, '__vite_ssr_import_meta__.url')
}

if (s) {
return {
code: s.toString(),
Expand Down
4 changes: 2 additions & 2 deletions packages/web-worker/src/shared-worker.ts
@@ -1,7 +1,7 @@
import { MessageChannel, type MessagePort as NodeMessagePort } from 'node:worker_threads'
import type { InlineWorkerContext, Procedure } from './types'
import { InlineWorkerRunner } from './runner'
import { debug, getRunnerOptions } from './utils'
import { debug, getFileIdFromUrl, getRunnerOptions } from './utils'

interface SharedInlineWorkerContext extends Omit<InlineWorkerContext, 'onmessage' | 'postMessage' | 'self' | 'global'> {
onconnect: Procedure | null
Expand Down Expand Up @@ -101,7 +101,7 @@ export function createSharedWorkerConstructor(): typeof SharedWorker {

const runner = new InlineWorkerRunner(runnerOptions, context)

const id = (url instanceof URL ? url.toString() : url).replace(/^file:\/+/, '/')
const id = getFileIdFromUrl(url)

this._vw_name = id

Expand Down
8 changes: 8 additions & 0 deletions packages/web-worker/src/utils.ts
Expand Up @@ -80,3 +80,11 @@ export function getRunnerOptions(): any {
state,
}
}

export function getFileIdFromUrl(url: URL | string) {
if (!(url instanceof URL))
url = new URL(url, self.location.origin)
if (url.protocol === 'http:' || url.protocol === 'https:')
return url.pathname
return url.toString().replace(/^file:\/+/, '/')
}
4 changes: 2 additions & 2 deletions packages/web-worker/src/worker.ts
@@ -1,6 +1,6 @@
import type { CloneOption, DefineWorkerOptions, InlineWorkerContext, Procedure } from './types'
import { InlineWorkerRunner } from './runner'
import { createMessageEvent, debug, getRunnerOptions } from './utils'
import { createMessageEvent, debug, getFileIdFromUrl, getRunnerOptions } from './utils'

export function createWorkerConstructor(options?: DefineWorkerOptions): typeof Worker {
const runnerOptions = getRunnerOptions()
Expand Down Expand Up @@ -66,7 +66,7 @@ export function createWorkerConstructor(options?: DefineWorkerOptions): typeof W

const runner = new InlineWorkerRunner(runnerOptions, context)

const id = (url instanceof URL ? url.toString() : url).replace(/^file:\/+/, '/')
const id = getFileIdFromUrl(url)

this._vw_name = id

Expand Down
19 changes: 19 additions & 0 deletions test/core/test/url-ssr.test.ts
@@ -0,0 +1,19 @@
// @vitest-environment node

import { fileURLToPath, pathToFileURL } from 'node:url'
import { dirname, resolve } from 'pathe'
import { expect, it } from 'vitest'

it('correctly resolves new assets URL paths', () => {
const urlCss = new URL('../src/file-css.css', import.meta.url)
expect(urlCss.toString()).toBe(
pathToFileURL(resolve(dirname(fileURLToPath(import.meta.url)), '../src/file-css.css')).toString(),
)
})

it('doesn\'t resolve aliases for new URL in SSR', () => {
const urlAlias = new URL('#/file-css.css', import.meta.url)
expect(urlAlias.toString()).toBe(
pathToFileURL(`${fileURLToPath(import.meta.url)}#/file-css.css`).toString().replace('%23', '#'),
)
})
13 changes: 13 additions & 0 deletions test/core/test/url-web.test.ts
@@ -0,0 +1,13 @@
// @vitest-environment jsdom

import { expect, it } from 'vitest'

it('correctly resolves new assets URL paths', () => {
const urlCss = new URL('../src/file-css.css', import.meta.url)
expect(urlCss.toString()).toBe('http://localhost:3000/src/file-css.css')
})

it('correctly resolves aliased URL paths', () => {
const urlAlias = new URL('#/file-css.css', import.meta.url)
expect(urlAlias.toString()).toBe('http://localhost:3000/src/file-css.css')
})
6 changes: 4 additions & 2 deletions test/web-worker/test/init.test.ts
Expand Up @@ -75,11 +75,13 @@ it('self injected into worker and its deps should be equal', async () => {
expect.assertions(4)
expect(await testSelfWorker(new MySelfWorker())).toBeTruthy()
// wait for clear worker mod cache
await sleep(500)
await sleep(0)
expect(await testSelfWorker(new MySelfWorker())).toBeTruthy()

await sleep(0)

expect(await testSelfWorker(new Worker(new URL('../src/selfWorker.ts', import.meta.url)))).toBeTruthy()
// wait for clear worker mod cache
await sleep(500)
await sleep(0)
expect(await testSelfWorker(new Worker(new URL('../src/selfWorker.ts', import.meta.url)))).toBeTruthy()
})

0 comments on commit c66a0a2

Please sign in to comment.