deno.com

编写测试

在 Github 上编辑

在软件开发中最常见的任务之一是为现有代码编写测试。 Deno 有一个内置的测试运行器,使这项工作变得非常容易。

首先,我们从标准库导入断言语句。有很多选项,但我们在这里只导入最常用的选项。
import { assert, assertEquals } from "jsr:@std/assert";
使用测试运行器最简单的方法是只传递一个描述和一个回调函数
Deno.test("assert works correctly", () => {
  assert(true);
  assertEquals(1, 1);
});
在更复杂的场景中,我们经常需要有一些设置和拆卸代码,并在其中间加入一些步骤。使用内置的测试运行器,这也变得很简单。
Deno.test("testing steps", async (t) => {
  const file = await Deno.open("example.txt", {
    read: true,
    write: true,
    create: true,
  });
  const encoder = new TextEncoder();
  const data = encoder.encode("Hello world!");

  await t.step("write some bytes", async () => {
    const bytesWritten = await file.write(data);
    assertEquals(bytesWritten, data.length);
    await file.seek(0, Deno.SeekMode.Start);
  });

  await t.step("read some bytes", async () => {
    const buffer = new Uint8Array(data.length);
    await file.read(buffer);
    assertEquals(buffer, data);
  });

  file.close();
});
默认情况下,测试运行器使得自毁变得非常困难。对于每个测试,测试运行器都会检查以确保在测试期间创建的所有资源都已释放。在某些情况下,这种行为没有用处。我们可以使用更复杂的测试定义来禁用此行为
Deno.test({
  name: "leaky test",
  async fn() {
    await Deno.open("example.txt");
  },
  sanitizeResources: false,
});

使用 Deno CLI 在本地运行此示例

deno test --allow-read --allow-write https://github.com/denoland/deno-docs/blob/main/examples/scripts/writing_tests.ts

您找到您需要的了吗?

隐私政策