Skip to content

Jest compatibility API: mock.contexts is not supported #2810

@trivikr

Description

@trivikr

Clear and concise description of the problem

Jest added support for testing function context ("this") in Mock functions in jest@28.x
PR jestjs/jest#11235

Docs: https://jestjs.io/docs/mock-function-api#mockfnmockcontexts

It would be useful to have this in vitest too.

Suggested solution

mock.context is added in vitest, so that the following test code can be written

test("contexts", () => {
  const mockFn = vi.fn();
  expect(mockFn.mock.contexts).toHaveLength(0);

  const bindContext = { x : 1 };
  const boundMockFn = mockFn.bind(bindContext);
  boundMockFn();
  expect(mockFn.mock.contexts).toHaveLength(1);
  expect(mockFn.mock.contexts[0]).toBe(bindContext);

  const callContext = { x : 2 };
  mockFn.call(callContext);
  expect(mockFn.mock.contexts).toHaveLength(2);
  expect(mockFn.mock.contexts[1]).toBe(callContext);

  const applyContext = { x : 3 };
  mockFn.apply(applyContext);
  expect(mockFn.mock.contexts).toHaveLength(3);
  expect(mockFn.mock.contexts[2]).toBe(applyContext);
})

Alternative

Skip adding the support for context.

Additional context

This issue was noticed while adding support for transformation of jest to vi API in trivikr/vitest-codemod#80

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Approved

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions