从 v28 到 v29
将 Jest 从 v28 升级到 v29?本指南旨在帮助重构你的配置和测试。
¥Upgrading Jest from v28 to v29? This guide aims to help refactoring your configuration and tests.
兼容性
¥Compatibility
支持的 Node 版本为 14.15、16.10、18.0 及更高版本。
¥The supported Node versions are 14.15, 16.10, 18.0 and above.
快照格式
¥Snapshot format
正如 Jest 28 博客文章 中所宣布的,Jest 29 已将默认快照格式更改为 {escapeString: false, printBasicPrototype: false}
。
¥As announced in the Jest 28 blog post, Jest 29 has changed the default snapshot formatting to {escapeString: false, printBasicPrototype: false}
.
如果你想保留旧的行为,可以将 snapshotFormat
属性设置为:
¥If you want to keep the old behavior, you can set the snapshotFormat
property to:
+ snapshotFormat: {
+ escapeString: true,
+ printBasicPrototype: true
+ }
JSDOM 升级
¥JSDOM upgrade
jest-environment-jsdom
已将 jsdom
从 v19 升级到 v20。
¥jest-environment-jsdom
has upgraded jsdom
from v19 to v20.
如果你使用 jest-environment-jsdom
,则最低 TypeScript 版本设置为 4.5
。
¥If you use jest-environment-jsdom
, the minimum TypeScript version is set to 4.5
.
值得注意的是,jsdom@20
包含对 crypto.getRandomValues()
的支持,这意味着像 uuid
和 nanoid
这样在 Jest@28 中无法正常工作的软件包无需额外的 polyfill 即可工作。
¥Notably, jsdom@20
includes support for crypto.getRandomValues()
, which means packages like uuid
and nanoid
, which doesn't work properly in Jest@28, can work without extra polyfills.
pretty-format
ConvertAnsi
插件已从 pretty-format
包中删除,取而代之的是 jest-serializer-ansi-escapes
。
¥ConvertAnsi
plugin is removed from pretty-format
package in favour of jest-serializer-ansi-escapes
.
jest-mock
从 jest-mock
包导出 Mocked*
工具类型已更改。MaybeMockedDeep
和 MaybeMocked
现在分别导出为 Mocked
和 MockedShallow
;仅暴露了 MockedClass
、MockedFunction
和 MockedObject
的深度模拟变体。
¥Exports of Mocked*
utility types from jest-mock
package have changed. MaybeMockedDeep
and MaybeMocked
now are exported as Mocked
and MockedShallow
respectively; only deep mocked variants of MockedClass
, MockedFunction
and MockedObject
are exposed.
TypeScript
仅当你显式导入 Jest API 时,此页面中的 TypeScript 示例才会按照文档说明的方式工作:
¥The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:
import {expect, jest, test} from '@jest/globals';
有关如何使用 TypeScript 设置 Jest 的详细信息,请参阅 入门 指南。
¥Consult the Getting Started guide for details on how to setup Jest with TypeScript.
jest.mocked()
jest.mocked()
辅助方法现在默认封装传递对象的深层成员类型。如果你使用了以 true
作为第二个参数的方法,请将其删除以避免类型错误:
¥The jest.mocked()
helper method now wraps types of deep members of passed object by default. If you have used the method with true
as the second argument, remove it to avoid type errors:
- const mockedObject = jest.mocked(someObject, true);
+ const mockedObject = jest.mocked(someObject);
要具有旧的浅模拟行为,请将 {shallow: true}
作为第二个参数传递:
¥To have the old shallow mocked behavior, pass {shallow: true}
as the second argument:
- const mockedObject = jest.mocked(someObject);
+ const mockedObject = jest.mocked(someObject, {shallow: true});