aboutsummaryrefslogtreecommitdiff
path: root/docs/test/mocks.md
diff options
context:
space:
mode:
authorGravatar Colin McDonnell <colinmcd94@gmail.com> 2023-07-06 13:02:29 -0700
committerGravatar GitHub <noreply@github.com> 2023-07-06 13:02:29 -0700
commit109ebc14fda92bc2c84459b9911bef03b08f1b0a (patch)
treeaf707758802715fcb567ac88225e0c23e2974dbd /docs/test/mocks.md
parent95ddfcc4377350b1d604c39c36562bde45fad2a9 (diff)
downloadbun-109ebc14fda92bc2c84459b9911bef03b08f1b0a.tar.gz
bun-109ebc14fda92bc2c84459b9911bef03b08f1b0a.tar.zst
bun-109ebc14fda92bc2c84459b9911bef03b08f1b0a.zip
Various docs updates (#3437)
* Various docs updates * Add mocks page * Fix make * WebKit instructions * Update instructions * Updates * Update nodejs compat table * Document trusted deps * Tweak trustedDependencies docs * Document --exact * Update test docs * Tweaks * Boring * Remove redundant j * Undo makefile changes * Undo makefile changes * Update page title * Regen * Undo changes
Diffstat (limited to '')
-rw-r--r--docs/test/mocks.md55
1 files changed, 55 insertions, 0 deletions
diff --git a/docs/test/mocks.md b/docs/test/mocks.md
new file mode 100644
index 000000000..31b5dab41
--- /dev/null
+++ b/docs/test/mocks.md
@@ -0,0 +1,55 @@
+Create mocks with the `mock` function.
+
+```ts
+import { test, expect, mock } from "bun:test";
+const random = mock(() => Math.random());
+
+test("random", async () => {
+ const val = random();
+ expect(val).toBeGreaterThan(0);
+ expect(random).toHaveBeenCalled();
+ expect(random).toHaveBeenCalledTimes(1);
+});
+```
+
+The result of `mock()` is a new function that's been decorated with some additional properties.
+
+```ts
+import { mock } from "bun:test";
+const random = mock((multiplier: number) => multiplier * Math.random());
+
+random(2);
+random(10);
+
+random.mock.calls;
+// [[ 2 ], [ 10 ]]
+
+random.mock.results;
+// [
+// { type: "return", value: 0.6533907460954099 },
+// { type: "return", value: 0.6452713933037312 }
+// ]
+```
+
+## `.spyOn()`
+
+It's possible to track calls to a function without replacing it with a mock. Use `spyOn()` to create a spy; these spies can be passed to `.toHaveBeenCalled()` and `.toHaveBeenCalledTimes()`.
+
+```ts
+import { test, expect, spyOn } from "bun:test";
+
+const ringo = {
+ name: "Ringo",
+ sayHi() {
+ console.log(`Hello I'm ${this.name}`);
+ },
+};
+
+const spy = spyOn(ringo, "sayHi");
+
+test("spyon", () => {
+ expect(spy).toHaveBeenCalledTimes(0);
+ ringo.sayHi();
+ expect(spy).toHaveBeenCalledTimes(1);
+});
+```