Skip to content

Stub

一句话解释

stub 是 simplified replacement 那个只是返回 canned 响应 — 它 doesn't 验证如何它 是 called.

用大白话说

stub 是 simplest kind 的测试双. 它 replaces 真实函数但 仅做 one thing: 返回值 你 pre-配置. 它 doesn't 记录 calls or 验证任何事.

Think 的 stub 如 recorded 消息. 当你 call 它, 它 plays 后面相同响应每个时间. 它 doesn't care 如何许多次数你 called or 什么实参你 通过 — 它只是返回什么你 told 它到 返回.

Stubs 是 useful 当你 需要到 control 什么 dependency 返回但 don't 需要到 验证如何你的 code interacted 使用它. 例如, stubbing 配置函数到 总是返回 'production' 模式.

示例

javascript
// Stub: always returns 42
const stub = jest.fn().mockReturnValue(42);
console.log(stub()); // 42
console.log(stub()); // 42
// No verification of call count or args

stub 总是返回 42 regardless 的如何 or 如何许多次数它's called.

常见混淆

  • 容易混淆的对象: Mock

    关键区别: stub 仅 provides 返回值; mock 也设置上 expectations 关于如何它 应该是 called.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表