Skip to main content
On this page

@std/expect

Overview Jump to heading

This module provides Jest compatible expect assertion functionality.

import { expect } from "@std/expect";

const x = 6 * 7;
expect(x).toEqual(42);
expect(x).not.toEqual(0);

await expect(Promise.resolve(x)).resolves.toEqual(42);

Currently this module supports the following functions:

Only these functions are still not available:

  • Matchers:
    • toMatchSnapshot
    • toMatchInlineSnapshot
    • toThrowErrorMatchingSnapshot
    • toThrowErrorMatchingInlineSnapshot

The tracking issue to add support for unsupported parts of the API is https://github.com/denoland/std/issues/3964.

This module is largely inspired by x/expect module by Allain Lalonde.

Add to your project Jump to heading

deno add jsr:@std/expect

See all symbols in @std/expect on

什么是 expect? Jump to heading

一个兼容 Jest 的流式断言 API。与独立的断言函数不同, 您可以编写像 expect(value).toBe(1) 这样的预期,并能链式调用修饰符,如 .not.resolves.rejects

何时使用 @std/expect Jump to heading

如果您喜欢类似 Jest 的 API,具有流畅、易读的断言和丰富的匹配器, 尤其是在从 Jest 迁移时。

示例 Jump to heading

import { expect } from "@std/expect";

expect({ a: 1, b: 2 }).toMatchObject({ a: 1 });
await expect(Promise.resolve(42)).resolves.toBe(42);
expect([1, 2, 3]).toContain(2);

// 抛出异常和异步拒绝
expect(() => JSON.parse("{"))
  .toThrow(SyntaxError);
await expect(Promise.reject(new Error("boom")))
  .rejects.toThrow("boom");

// 浮点近似,正则匹配
expect(0.1 + 0.2).toBeCloseTo(0.3, 15);
expect("hello world").toMatch(/world/);

// 使用非对称匹配器
expect({ id: 1, name: "Ada" })
  .toEqual(expect.objectContaining({ name: expect.stringMatching(/^A/) }));

与 Deno.test 一起使用 Jump to heading

import { expect } from "@std/expect";
Deno.test("基本 expect 测试", () => {
  const value = 2 + 2;
  expect(value).toBe(4);
});

更多关于 Deno 中测试的信息,请参见 测试文档

小贴士 Jump to heading

  • 使用 toEqual 进行深度数据比较,使用 toBe 进行身份比较。
  • 优先使用 .resolves / .rejects 来处理 Promise。
  • 优先使用 .resolves / .rejects 来处理 Promise。
  • 使用 toStrictEqual 进行更严格的深度检查(无额外属性等)。
  • 需要时通过 expect.extend 扩展自定义匹配器。

你找到了你需要的东西吗?

编辑此页面
隐私政策