Expect 断言
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
编写测试时,经常需要验证值是否符合特定条件。expect 提供了一系列"匹配器",可帮助您验证不同类型的内容。
技巧
更多由 Jest 社区维护的匹配器,请查看 jest-extended。
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
信息
本页中的 TypeScript 示例仅在显式导入 Jest API 的情况下才能按文档所述正常工作:
import {expect, jest, test} from '@jest/globals';
有关如何设置 Jest 与 TypeScript 配合使用的详细信息,请查阅入门指南。
参数详解
- Expect 断言
- 修饰符
- 匹配器
.toBe(value).toHaveBeenCalled().toHaveBeenCalledTimes(number).toHaveBeenCalledWith(arg1, arg2, ...).toHaveBeenLastCalledWith(arg1, arg2, ...).toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....).toHaveReturned().toHaveReturnedTimes(number).toHaveReturnedWith(value).toHaveLastReturnedWith(value).toHaveNthReturnedWith(nthCall, value).toHaveLength(number).toHaveProperty(keyPath, value?).toBeCloseTo(number, numDigits?).toBeDefined().toBeFalsy().toBeGreaterThan(number | bigint).toBeGreaterThanOrEqual(number | bigint).toBeLessThan(number | bigint).toBeLessThanOrEqual(number | bigint).toBeInstanceOf(Class).toBeNull().toBeTruthy().toBeUndefined().toBeNaN().toContain(item).toContainEqual(item).toEqual(value).toMatch(regexp | string).toMatchObject(object).toMatchSnapshot(propertyMatchers?, hint?).toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot).toStrictEqual(value).toThrow(error?).toThrowErrorMatchingSnapshot(hint?).toThrowErrorMatchingInlineSnapshot(inlineSnapshot)
- 非对称匹配器
expect.anything()expect.any(constructor)expect.arrayContaining(array)expect.not.arrayContaining(array)expect.arrayOf(value)expect.not.arrayOf(value)expect.closeTo(number, numDigits?)expect.objectContaining(object)expect.not.objectContaining(object)expect.stringContaining(string)expect.not.stringContaining(string)expect.stringMatching(string | regexp)expect.not.stringMatching(string | regexp)