Skip to content

Commit

Permalink
fix: expect.getState().testPath always returns correct path (#6472)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Sep 11, 2024
1 parent 9560ab7 commit ac698b1
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 12 deletions.
8 changes: 6 additions & 2 deletions packages/expect/src/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export function setState<State extends MatcherState = MatcherState>(
): void {
const map = (globalThis as any)[MATCHERS_OBJECT]
const current = map.get(expect) || {}
Object.assign(current, state)
map.set(expect, current)
// so it keeps getters from `testPath`
const results = Object.defineProperties(current, {
...Object.getOwnPropertyDescriptors(current),
...Object.getOwnPropertyDescriptors(state),
})
map.set(expect, results)
}
13 changes: 3 additions & 10 deletions packages/vitest/src/integrations/chai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ export function createExpect(test?: TaskPopulated) {
// @ts-expect-error global is not typed
const globalState = getState(globalThis[GLOBAL_EXPECT]) || {}

const testPath = getTestFile(test)
setState<MatcherState>(
{
// this should also add "snapshotState" that is added conditionally
Expand All @@ -50,7 +49,9 @@ export function createExpect(test?: TaskPopulated) {
expectedAssertionsNumber: null,
expectedAssertionsNumberErrorGen: null,
environment: getCurrentEnvironment(),
testPath,
get testPath() {
return getWorkerState().filepath
},
currentTestName: test
? getTestName(test as Test)
: globalState.currentTestName,
Expand Down Expand Up @@ -111,14 +112,6 @@ export function createExpect(test?: TaskPopulated) {
return expect
}

function getTestFile(test?: TaskPopulated) {
if (test) {
return test.file.filepath
}
const state = getWorkerState()
return state.filepath
}

const globalExpect = createExpect()

Object.defineProperty(globalThis, GLOBAL_EXPECT, {
Expand Down
5 changes: 5 additions & 0 deletions test/core/test/basic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import { assert, expect, it, suite, test } from 'vitest'
import { two } from '../src/submodule'
import { timeout } from '../src/timeout'

const testPath = expect.getState().testPath
if (!testPath || !testPath.includes('basic.test.ts')) {
throw new Error(`testPath is not correct: ${testPath}`)
}

test('Math.sqrt()', async () => {
assert.equal(Math.sqrt(4), two)
assert.equal(Math.sqrt(2), Math.SQRT2)
Expand Down

0 comments on commit ac698b1

Please sign in to comment.