diff --git a/packages/expect/src/state.ts b/packages/expect/src/state.ts index efa26c692c07..dade3622e001 100644 --- a/packages/expect/src/state.ts +++ b/packages/expect/src/state.ts @@ -39,6 +39,10 @@ export function setState( ): 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) } diff --git a/packages/vitest/src/integrations/chai/index.ts b/packages/vitest/src/integrations/chai/index.ts index 72ce87d34c5c..2b2cfcbe912e 100644 --- a/packages/vitest/src/integrations/chai/index.ts +++ b/packages/vitest/src/integrations/chai/index.ts @@ -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( { // this should also add "snapshotState" that is added conditionally @@ -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, @@ -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, { diff --git a/test/core/test/basic.test.ts b/test/core/test/basic.test.ts index d775423c442b..9c6aac68f8eb 100644 --- a/test/core/test/basic.test.ts +++ b/test/core/test/basic.test.ts @@ -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)