Skip to content

Commit ac698b1

Browse files
authoredSep 11, 2024··
fix: expect.getState().testPath always returns correct path (#6472)
1 parent 9560ab7 commit ac698b1

File tree

3 files changed

+14
-12
lines changed

3 files changed

+14
-12
lines changed
 

‎packages/expect/src/state.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ export function setState<State extends MatcherState = MatcherState>(
3939
): void {
4040
const map = (globalThis as any)[MATCHERS_OBJECT]
4141
const current = map.get(expect) || {}
42-
Object.assign(current, state)
43-
map.set(expect, current)
42+
// so it keeps getters from `testPath`
43+
const results = Object.defineProperties(current, {
44+
...Object.getOwnPropertyDescriptors(current),
45+
...Object.getOwnPropertyDescriptors(state),
46+
})
47+
map.set(expect, results)
4448
}

‎packages/vitest/src/integrations/chai/index.ts

+3-10
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ export function createExpect(test?: TaskPopulated) {
3939
// @ts-expect-error global is not typed
4040
const globalState = getState(globalThis[GLOBAL_EXPECT]) || {}
4141

42-
const testPath = getTestFile(test)
4342
setState<MatcherState>(
4443
{
4544
// this should also add "snapshotState" that is added conditionally
@@ -50,7 +49,9 @@ export function createExpect(test?: TaskPopulated) {
5049
expectedAssertionsNumber: null,
5150
expectedAssertionsNumberErrorGen: null,
5251
environment: getCurrentEnvironment(),
53-
testPath,
52+
get testPath() {
53+
return getWorkerState().filepath
54+
},
5455
currentTestName: test
5556
? getTestName(test as Test)
5657
: globalState.currentTestName,
@@ -111,14 +112,6 @@ export function createExpect(test?: TaskPopulated) {
111112
return expect
112113
}
113114

114-
function getTestFile(test?: TaskPopulated) {
115-
if (test) {
116-
return test.file.filepath
117-
}
118-
const state = getWorkerState()
119-
return state.filepath
120-
}
121-
122115
const globalExpect = createExpect()
123116

124117
Object.defineProperty(globalThis, GLOBAL_EXPECT, {

‎test/core/test/basic.test.ts

+5
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@ import { assert, expect, it, suite, test } from 'vitest'
22
import { two } from '../src/submodule'
33
import { timeout } from '../src/timeout'
44

5+
const testPath = expect.getState().testPath
6+
if (!testPath || !testPath.includes('basic.test.ts')) {
7+
throw new Error(`testPath is not correct: ${testPath}`)
8+
}
9+
510
test('Math.sqrt()', async () => {
611
assert.equal(Math.sqrt(4), two)
712
assert.equal(Math.sqrt(2), Math.SQRT2)

0 commit comments

Comments
 (0)
Please sign in to comment.