aboutsummaryrefslogtreecommitdiff
path: root/docs/guides/test/spy-on.md
blob: 3a43b236735e4d9ad1e1f1270f123f534b17c048 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
---
name: Spy on methods in `bun test`
---

Use the `spyOn` utility to track method calls with Bun's test runner.

```ts
import { test, expect, spyOn } from "bun:test";

const leo = {
  name: "Leonard",
  sayHi(thing: string) {
    console.log(`Sup I'm ${this.name} and I like ${thing}`);
  },
};

const spy = spyOn(leo, "sayHi");
```

---

Once the spy is created, it can be used to write `expect` assertions relating to method calls.

```ts-diff
  import { test, expect, spyOn } from "bun:test";

  const leo = {
    name: "Leonardo",
    sayHi(thing: string) {
      console.log(`Sup, I'm ${this.name} and I like ${thing}`);
    },
  };

  const spy = spyOn(leo, "sayHi");

+ test("turtles", ()=>{
+   expect(spy).toHaveBeenCalledTimes(0);
+   leo.sayHi("pizza");
+   expect(spy).toHaveBeenCalledTimes(0);
+   expect(spy.mock.calls).toEqual([[ "pizza" ]]);
+ })
```

---

See [Docs > Test Runner > Mocks](/docs/test/mocks) for complete documentation on mocking with the Bun test runner.