Skip to content

Commit

Permalink
fix: clear mocks between tests (#2857)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Feb 13, 2023
1 parent 4ea1f1d commit c420cb7
Show file tree
Hide file tree
Showing 6 changed files with 37 additions and 2 deletions.
2 changes: 2 additions & 0 deletions packages/vitest/src/runtime/entry.ts
Expand Up @@ -144,6 +144,8 @@ export async function run(files: string[], config: ResolvedConfig, executor: Vit

// reset after tests, because user might call `vi.setConfig` in setupFile
vi.resetConfig()
// mocks should not affect different files
vi.restoreAllMocks()
}
})
}
Expand Down
1 change: 1 addition & 0 deletions test/single-thread/package.json
@@ -1,5 +1,6 @@
{
"name": "@vitest/test-single-thread",
"type": "module",
"private": true,
"scripts": {
"test": "vitest",
Expand Down
9 changes: 8 additions & 1 deletion test/single-thread/test/a.test.ts
@@ -1,4 +1,11 @@
import { it } from 'vitest'
import fs from 'node:fs'
import { expect, it, vi } from 'vitest'
import { timeout } from './timeout'

// this file is running first, it should not affect file "b.test.ts"
it('mock is mocked', () => {
vi.spyOn(fs, 'readFileSync').mockReturnValue('mocked')
expect(fs.readFileSync('')).toBe('mocked')
})

it('timeout', () => new Promise(resolve => setTimeout(resolve, timeout)))
16 changes: 15 additions & 1 deletion test/single-thread/test/b.test.ts
@@ -1,4 +1,18 @@
import { it } from 'vitest'
import fs from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'pathe'
import { expect, it } from 'vitest'
import { timeout } from './timeout'

// this file is running second, it should not be affected by mock in "a.test.ts"
it('mock is mocked', () => {
expect(fs.readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), './timeout.ts'), 'utf-8')).toMatchInlineSnapshot(`
"export const timeout = 200
export const mockedFn = function () {
return 'original'
}
"
`)
})

it('timeout', () => new Promise(resolve => setTimeout(resolve, timeout)))
3 changes: 3 additions & 0 deletions test/single-thread/test/timeout.ts
@@ -1 +1,4 @@
export const timeout = 200
export const mockedFn = function () {
return 'original'
}
8 changes: 8 additions & 0 deletions test/single-thread/vitest.config.ts
@@ -1,7 +1,15 @@
import { defineConfig } from 'vite'
import { BaseSequencer } from 'vitest/node'

export default defineConfig({
test: {
threads: false,
sequence: {
sequencer: class Sequences extends BaseSequencer {
public async sort(files: string[]): Promise<string[]> {
return files.sort()
}
},
},
},
})

0 comments on commit c420cb7

Please sign in to comment.