Skip to content

Mocking changes returned promises #5647

@miguel-leon

Description

@miguel-leon

Describe the bug

A promise returned by a mocked function or methods, changes a returned promise.
i.e., saving the promise in a variable before returning it and then comparing it to what's returned outside the function with === evaluates to false.

I can't find documentation for this and it doesn't happen with jest, so I suppose it's unintended.

Code from the StackBlitz link just in case:

class Foo {
	x?: Promise<void>;

	bar() {
		return this.x = Promise.resolve();
	}
}

Foo.prototype.bar = vi.fn(Foo.prototype.bar);


test('should work', async () => {
	const foo = new Foo();
	const y = foo.bar();
	expect(foo.x === y).toBe(true); // errors
});

Reproduction

https://stackblitz.com/edit/vitest-dev-vitest-zkjejn?file=src%2Fbasic.ts

System Info

irrelevant

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

    Status

    Has plan

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions