Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add vi.setConfig helper #2293

Merged
merged 4 commits into from Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/api/index.md
Expand Up @@ -2598,6 +2598,12 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo

Will call [`.mockReset()`](/api/#mockreset) on all spies. This will clear mock history and reset its implementation to an empty function (will return `undefined`).

### vi.resetConfig

- **Type**: `RuntimeConfig`

If [`vi.setConfig`](/api/#vi-setconfig) was called before, this will reset config to the original state.

### vi.resetModules

- **Type**: `() => Vitest`
Expand Down Expand Up @@ -2691,6 +2697,12 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo
vi.useRealTimers()
```

### vi.setConfig

- **Type**: `RuntimeConfig`

Updates config for the current test file. You can only affect values that are used, when executing tests.

### vi.spyOn

- **Type:** `<T, K extends keyof T>(object: T, method: K, accessType?: 'get' | 'set') => MockInstance`
Expand Down
23 changes: 23 additions & 0 deletions packages/vitest/src/integrations/vi.ts
@@ -1,6 +1,7 @@
import type { FakeTimerInstallOpts } from '@sinonjs/fake-timers'
import { parseStacktrace } from '../utils/source-map'
import type { VitestMocker } from '../runtime/mocker'
import type { ResolvedConfig, RuntimeConfig } from '../types'
import { getWorkerState, resetModules, setTimeout } from '../utils'
import { FakeTimers } from './mock/timers'
import type { EnhancedSpy, MaybeMocked, MaybeMockedDeep, MaybePartiallyMocked, MaybePartiallyMockedDeep } from './spy'
Expand Down Expand Up @@ -260,6 +261,28 @@ class VitestUtils {
// like in import('./example').then(...)
await new Promise(resolve => setTimeout(resolve, 1)).then(() => Promise.resolve())
}

private _config: null | ResolvedConfig = null

/**
* Updates runtime config. You can only change values that are used when executing tests.
*/
public setConfig(config: RuntimeConfig) {
const state = getWorkerState()
if (!this._config)
this._config = { ...state.config }
Object.assign(state.config, config)
}

/**
* If config was changed with `vi.setConfig`, this will reset it to the original state.
*/
public resetConfig() {
if (this._config) {
const state = getWorkerState()
state.config = { ...this._config }
}
}
}

export const vitest = new VitestUtils()
Expand Down
4 changes: 4 additions & 0 deletions packages/vitest/src/runtime/entry.ts
@@ -1,6 +1,7 @@
import { promises as fs } from 'fs'
import type { EnvironmentOptions, ResolvedConfig, VitestEnvironment } from '../types'
import { getWorkerState, resetModules } from '../utils'
import { vi } from '../integrations/vi'
import { envs } from '../integrations/env'
import { setupGlobalEnv, withEnv } from './setup'
import { startTests } from './run'
Expand Down Expand Up @@ -75,6 +76,9 @@ export async function run(files: string[], config: ResolvedConfig): Promise<void
await startTests([file], config)

workerState.filepath = undefined

// reset after tests, because user might call `vi.setConfig` in setupFile
vi.resetConfig()
}
})
}
Expand Down
12 changes: 12 additions & 0 deletions packages/vitest/src/types/config.ts
Expand Up @@ -558,3 +558,15 @@ export interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'f

typecheck: TypecheckConfig
}

export type RuntimeConfig = Pick<
UserConfig,
| 'allowOnly'
| 'testTimeout'
| 'hookTimeout'
| 'clearMocks'
| 'mockReset'
| 'restoreMocks'
| 'fakeTimers'
| 'maxConcurrency'
>
13 changes: 13 additions & 0 deletions test/core/test/vi.spec.ts
Expand Up @@ -4,6 +4,7 @@

import type { MockedFunction, MockedObject } from 'vitest'
import { describe, expect, test, vi } from 'vitest'
import { getWorkerState } from 'vitest/src/utils'

const expectType = <T>(obj: T) => obj

Expand Down Expand Up @@ -64,6 +65,18 @@ describe('testing vi utils', () => {
})
})

test('can change config', () => {
const state = getWorkerState()
expect(state.config.hookTimeout).toBe(10000)
expect(state.config.clearMocks).toBe(false)
vi.setConfig({ hookTimeout: 6000, clearMocks: true })
expect(state.config.hookTimeout).toBe(6000)
expect(state.config.clearMocks).toBe(true)
vi.resetConfig()
expect(state.config.hookTimeout).toBe(10000)
expect(state.config.clearMocks).toBe(false)
})

// TODO: it's unstable in CI, skip until resolved
test.skip('loads unloaded module', async () => {
let mod: any
Expand Down