On this page
@std/testing
Overview Jump to heading
This package provides utilities for testing.
import { assertSpyCalls, spy } from "@std/testing/mock";
import { FakeTime } from "@std/testing/time";
function secondInterval(cb: () => void): number {
return setInterval(cb, 1000);
}
Deno.test("secondInterval calls callback every second and stops after being cleared", () => {
using time = new FakeTime();
const cb = spy();
const intervalId = secondInterval(cb);
assertSpyCalls(cb, 0);
time.tick(500);
assertSpyCalls(cb, 0);
time.tick(500);
assertSpyCalls(cb, 1);
time.tick(3500);
assertSpyCalls(cb, 4);
clearInterval(intervalId);
time.tick(1000);
assertSpyCalls(cb, 4);
});
Add to your project Jump to heading
deno add jsr:@std/testing
See all symbols in @std/testing on
测试 Jump to heading
测试是一种验证代码行为符合预期的实践。它帮助及早发现错误,确保代码质量,并在进行修改时提供信心。
查看Deno 测试示例了解实际用法。
为什么使用 @std/testing Jump to heading
结合 Deno 内置的 Deno.test,使用这些工具编写更清晰的规范,模拟依赖,伪造定时器,创建快照。
示例 Jump to heading
import { afterEach, beforeEach, describe, it } from "@std/testing/bdd";
import { assertSpyCalls, spy } from "@std/testing/mock";
import { FakeTime } from "@std/testing/time";
describe("interval", () => {
let time: FakeTime;
beforeEach(() => (time = new FakeTime()));
afterEach(() => time.restore());
it("ticks", () => {
const cb = spy();
const id = setInterval(cb, 1000);
time.tick(3000);
assertSpyCalls(cb, 3);
clearInterval(id);
});
});
快照测试 Jump to heading
import { assertSnapshot } from "@std/testing/snapshot";
Deno.test("user json snapshot", async (t) => {
const user = { id: 1, name: "Ada", tags: ["admin", "ops"] };
await assertSnapshot(t, user);
});
Stub 全局方法 Jump to heading
import { stub } from "@std/testing/mock";
import { assertEquals } from "@std/assert";
Deno.test("stub Math.random", () => {
const s = stub(Math, "random", () => 0.5);
try {
assertEquals(Math.random(), 0.5);
} finally {
s.restore();
}
});
使用 returnsNext 编排序列 Jump to heading
import { returnsNext } from "@std/testing/mock";
import { assertEquals, assertThrows } from "@std/assert";
Deno.test("returnsNext sequences values and errors", () => {
const next = returnsNext([1, 2, new Error("boom"), 3]);
assertEquals(next(), 1);
assertEquals(next(), 2);
assertThrows(() => next(), Error, "boom");
assertEquals(next(), 3);
});
监听并断言调用参数 Jump to heading
import { assertSpyCallArgs, assertSpyCalls, spy } from "@std/testing/mock";
Deno.test("spy captures calls and args", () => {
const sum = spy((a: number, b: number) => a + b);
sum(3, 4);
sum(5, 6);
assertSpyCalls(sum, 2);
assertSpyCallArgs(sum, 0, [3, 4]);
});
小贴士 Jump to heading
- 结合
@std/assert或@std/expect使用断言。 - 使用
FakeTime有确定性地测试定时器和Date.now()。 - 在
afterEach或finally块中恢复 stub/spy,避免状态泄露。 - 将快照文件提交到版本控制,以捕获意外更改。