Skip to content

spyOn data properties #11062

Description

@Arthri

Clear and concise description of the problem

I want to be able to spy on data properties in JavaScript. I am trying to spy on octokit.rest to determine if any code paths try to use the REST API.

Suggested solution

The implementation for spyOn could be tweaked to allow properties as well, thereby making the call spyOn(obj, "property") valid. The original value of the property is saved, and the property is converted into an accessor property with a getter and a setter.

If the target member is an accessor property, and error is raised. Spying on accessor properties is already possible through spyOn(obj, "property", "get").

Alternative

There should be a warning in the logs or in the documentation that spyOn(obj, "property", "get") on a data property causes obj.property to become undefined. Spies aren't meant to change the implementation and in this case they observably do.

it("", () => {
  const obj = { key: "value" };
  const spy = vi.spyOn(obj, "key", "get");

  console.log(obj.key); // undefined
});

Additional context

It's possible to work around the issue by writing this instead

it("", () => {
  const obj = { key: "value" };
  const value = obj.key;
  const spy = vi.spyOn(obj, "key", "get").mockImplementation(() => value);

  console.log(obj.key);
});

Validations

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions