vitest icon indicating copy to clipboard operation
vitest copied to clipboard

A fixture named `task` breaks `expect` from the test context

Open sheremet-va opened this issue 3 weeks ago • 2 comments

A fixture named task replaces context.task. The expect from the test context is created lazily from context.task, so after fixtures run it gets the fixture value instead of the test:

  • a failed expect.soft passes
  • toMatchInlineSnapshot throws TypeError: Cannot read properties of undefined (reading 'filepath')

The imported expect is not affected.

Reproduction

Vitest 5.1.0:

import { test as baseTest } from 'vitest'

const test = baseTest.extend('task', () => ({ title: 'write docs', done: false }))

test('soft assertion fails', ({ task, expect }) => {
  // passes
  expect.soft(task.done).toBe(true)
})

test('inline snapshot passes', ({ task, expect }) => {
  // TypeError: Cannot read properties of undefined (reading 'filepath')
  expect(task.title).toMatchInlineSnapshot(`"write docs"`)
})

The expect and bench getters in extendTaskContext (packages/vitest/src/runtime/runners/test.ts) read context.task when they are first accessed. They should use the test that the context was created for.

Related: a fixture named expect or bench throws TypeError: Cannot set property expect of function() {...}, because both are getters without a setter. The types accept both fixtures.

sheremet-va avatar Nov 10 '26 08:11 sheremet-va

I'd like to work on this issue.

I've looked into extendTaskContext() and understand that the lazy getters for expect and bench rely on context.task, which can be overwritten by a fixture.

I'd like to investigate a fix that preserves the original test reference and add regression tests covering fixtures named task, expect, and bench.

Could this issue please be labelled approved so I can submit a PR?

hrishikeshpathak1009 avatar Nov 10 '26 13:11 hrishikeshpathak1009

Looked into extendTaskContext in packages/vitest/src/runtime/runners/test.ts:

  1. task fixture overriding: Capturing const task = context.task in the outer function scope ensures createExpect(task) and createBench(task) bind to the original Task instance regardless of whether a fixture later shadows context.task.
  2. expect and bench fixtures: Marking expect and bench descriptors with configurable: true and a setter (or allowing assignment) resolves the TypeError: Cannot set property expect when users define fixtures with those names.

I have a branch with this fix and regression tests covering fixtures named task, expect, and bench. Happy to open the PR directly.

YK-03 avatar Nov 19 '26 13:11 YK-03