Skip to content

vi.fn() performs an extra _await_ leading to mismatching behaviour when compared with normal function #5747

@dubzzz

Description

@dubzzz

Describe the bug

Replacing vi.fn(async () => {}) by async () => {} may lead to different results.

In some cases, the ordering of asynchronous tasks might be key. In fast-check, we have a scheduler able to help our users to automatically detect potential race conditions leading to bugs in their code. In order to test it, we used to rely on Jest but recently we moved to Vitest to benefit from ES Module support.

While playing with vi.fn() I encountered some issues related to when promises resolved: the order order is not consistent with a version not relying on vi.fn().

Reproduction

Here is an example highlighting the difference I encounter (diff between no vi.fn() or manual version of it and vi.fn()):

import { vi, test, expect } from "vitest";

// Passes!
test("should pass without vi.fn()", async () => {
  let obj = { done: false };
  const f = async () => {};
  Promise.resolve()
    .then(() => {})
    .then(() => (obj.done = true));
  await f();
  expect(obj.done).toBe(false);
});

// It should pass, but it fails!
test("should pass with vi.fn()", async () => {
  let obj = { done: false };
  const f = vi.fn(async () => {});
  Promise.resolve()
    .then(() => {})
    .then(() => (obj.done = true));
  await f();
  expect(obj.done).toBe(false);
});

System Info

System:
    OS: Windows 11 10.0.22621
    CPU: (4) x64 Intel(R) Core(TM) i5-3570K CPU @ 3.40GHz
    Memory: 1.25 GB / 7.89 GB
  Binaries:
    Node: 20.8.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.21 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 10.2.3 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Chromium (123.0.2420.97)
    Internet Explorer: 11.0.22621.3527
  npmPackages:
    vitest: ^1.5.3 => 1.5.3

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p3-minor-bugAn edge case that only affects very specific usage (priority)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions