# prefer-spy-on

Rule `vitest/prefer-spy-on`. Enforce using `vi.spyOn`

- Source: vitest
- Technologies: Testing
- Kind: style
- Needs type information: no
- Autofix: yes, in at least one linter
- Reach: 0 weekly downloads of presets that enable it
- Trend: 0% last quarter
- Rank: #1692 by reach

## Linters

| Linter | Rule name | Recommended | Autofix | Details | Docs |
| --- | --- | --- | --- | --- | --- |
| ESLint | `vitest/prefer-spy-on` | no | safe | package `@vitest/eslint-plugin` | [docs](https://github.com/vitest-dev/eslint-plugin-vitest/blob/main/docs/rules/prefer-spy-on.md) |
| Oxlint | `vitest/prefer-spy-on` | no | safe | plugin `vitest`, category style | [docs](https://oxc.rs/docs/guide/usage/linter/rules/vitest/prefer-spy-on.html) |
| Biome | `nursery/useSpyOn` | no | unsafe | group nursery, since 2.6.8 | [docs](https://biomejs.dev/linter/rules/use-spy-on/) |

## Code examples

### Incorrect: the rule reports this

```js
Date.now = jest.fn();
```

```js
Date.now = vi.fn(() => 10);
```

```js
window.fetch = jest.fn().mockResolvedValue(response);
```

### Correct: the rule accepts this

```js
jest.spyOn(Date, "now");
jest.spyOn(Date, "now").mockImplementation(() => 10);
vi.spyOn(window, "fetch").mockResolvedValue(response);
const mock = jest.fn();
const mocks = { now: vi.fn() };
```

Examples from the Biome documentation.

## Enable it

### ESLint: `eslint.config.js`

```js
import vitest from "@vitest/eslint-plugin";

export default [
  {
    plugins: { vitest },
    rules: {
      "vitest/prefer-spy-on": "error",
    },
  },
];
```

### Oxlint: `.oxlintrc.json`

```json
{
  "plugins": [
    "vitest"
  ],
  "rules": {
    "vitest/prefer-spy-on": "error"
  }
}
```

### Biome: `biome.json`

```json
{
  "linter": {
    "rules": {
      "nursery": {
        "useSpyOn": "error"
      }
    }
  }
}
```

## Related rules

- [jest/prefer-spy-on](https://lintradar.dev/rules/jest/prefer-spy-on.md): Suggest using `jest.spyOn()`
- [vitest/prefer-importing-vitest-globals](https://lintradar.dev/rules/vitest/prefer-importing-vitest-globals.md): Enforce importing Vitest globals
- [vitest/prefer-strict-equal](https://lintradar.dev/rules/vitest/prefer-strict-equal.md): Enforce strict equal over equal
- [vitest/prefer-hooks-on-top](https://lintradar.dev/rules/vitest/prefer-hooks-on-top.md): Enforce having hooks before any test cases
- [vitest/prefer-to-contain](https://lintradar.dev/rules/vitest/prefer-to-contain.md): Enforce using toContain()
- [vitest/prefer-equality-matcher](https://lintradar.dev/rules/vitest/prefer-equality-matcher.md): Enforce using the built-in equality matchers

---

Web page: https://lintradar.dev/rules/vitest/prefer-spy-on. Data from npm and the linters' documentation, collected Dec 4, 2026. Site guide for agents: https://lintradar.dev/llms.txt
