用于 Jest 的自定义 Console
对象匹配器,用于测试 WordPress 中的 JavaScript 代码。
该软件包会将 console.error、console.info、console.log 和 console.warn 函数转换为模拟函数(mock),并跟踪它们的调用。
只要被测代码调用上述任一 console 方法,它还会强制要求使用相关匹配器之一。
这意味着,当 console.error
被执行时,你需要使用 .toHaveErrored() 或 .toHaveErroredWith( arg1, arg2, ... ) 进行断言;当调用 console.info、console.log 或 console.warn 时,则使用对应的方法。
否则测试将会失败!这是一个有意为之的设计决策,有助于在
升级依赖库时检测弃用警告,或在重构代码时发现较小错误。
安装
安装模块:
npm install @wordpress/jest-console --save-dev
注意:该软件包需要长期支持状态的 Node.js 版本(请查看 Active LTS 或 Maintenance LTS 发布版本)。它与旧版本不兼容。
设置
最简单的设置方式是使用 Jest 的 setupFilesAfterEnv 配置选项:
"jest": {
"setupFilesAfterEnv": [
"@wordpress/jest-console"
]
},
用法
.toHaveErrored()
使用 .toHaveErrored 来确保调用了 console.error 函数。
例如,假设你有一个 drinkAll( flavor ) 函数,它会让你喝下所有可用饮品。
你可能想检查该函数是否会为 'octopus' 调用 console.error,因为 'octopus' 风味确实
很奇怪,为什么会有东西是章鱼味的?你可以使用以下测试套件来实现:
describe( 'drinkAll', () => {
test( 'drinks something lemon-flavored', () => {
drinkAll( 'lemon' );
expect( console ).not.toHaveErrored();
} );
test( 'errors when something is octopus-flavored', () => {
drinkAll( 'octopus' );
expect( console ).toHaveErrored();
} );
} );
.toHaveErroredWith( arg1, arg2, … )
使用 .toHaveErroredWith 来确保调用了 console.error 函数,并传入了
特定参数。
例如,再次假设你有一个 drinkAll( flavor ) 函数,它会让你喝下所有可用饮品。
你可能想检查该函数是否会为 'octopus' 使用特定消息调用 console.error,因为'octopus' 风味确实很奇怪,为什么会有东西是章鱼味的?要确保这一点,你可以编写:
describe( 'drinkAll', () => {
test( 'errors with message when something is octopus-flavored', () => {
drinkAll( 'octopus' );
expect( console ).toHaveErroredWith(
'Should I really drink something that is octopus-flavored?'
);
} );
} );
.toHaveInformed()
使用 .toHaveInformed 来确保调用了 console.info 函数。
用法与 .toHaveErrored() 几乎完全相同。
.toHaveInformedWith( arg1, arg2, … )
使用 .toHaveInformedWith 来确保调用了 console.info 函数,并传入了
特定参数。
用法与 .toHaveErroredWith() 几乎完全相同。
.toHaveLogged()
使用 .toHaveLogged 来确保调用了 console.log 函数。
用法与 .toHaveErrored() 几乎完全相同。
.toHaveLoggedWith( arg1, arg2, … )
使用 .toHaveLoggedWith 来确保调用了 console.log 函数,并传入了
特定参数。
用法与 .toHaveErroredWith() 几乎完全相同。
.toHaveWarned()
使用 .toHaveWarned 来确保调用了 console.warn 函数。
用法与 .toHaveErrored() 几乎完全相同。
.toHaveWarnedWith( arg1, arg2, … )
使用 .toHaveWarneddWith 来确保调用了 console.warn 函数,并传入了
特定参数。
用法与 .toHaveErroredWith() 几乎完全相同。
为该软件包做贡献
这是一个独立软件包,属于 Gutenberg 项目。该项目被组织为 monorepo。它由多个自包含软件包组成,每个软件包都有特定用途。该 monorepo 中的软件包会发布到 npm,并被 WordPress 以及其他软件项目使用。
要了解有关为该软件包或整个 Gutenberg 项目做出贡献的更多信息,请阅读项目的主 贡献者指南。