迁移到 Shoehorn
为什么使用 shoehorn?
shoehorn 允许你在测试中传递部分数据,同时让 TypeScript 保持满意。它用类型安全的替代方案替换 as 断言。
仅测试代码。 绝不在生产代码中使用 shoehorn。
测试中使用 as 的问题:
- 被训练为不使用它
- 必须手动指定目标类型
- 对于故意错误的数据需要双重
as(as unknown as Type)
安装
npm i @total-typescript/shoehorn
迁移模式
大型对象但只有少量需要的属性
之前:
type Request = {
body: { id: string };
headers: Record<string, string>;
cookies: Record<string, string>;
// ...20 more properties
};
it("gets user by id", () => {
// Only care about body.id but must fake entire Request
getUser({
body: { id: "123" },
headers: {},
cookies: {},
// ...fake all 20 properties
});
});
之后:
import { fromPartial } from "@total-typescript/shoehorn";
it("gets user by id", () => {
getUser(
fromPartial({
body: { id: "123" },
}),
);
});
as Type → fromPartial()
之前:
getUser({ body: { id: "123" } } as Request);
之后:
import { fromPartial } from "@total-typescript/shoehorn";
getUser(fromPartial({ body: { id: "123" } }));
as unknown as Type → fromAny()
之前:
getUser({ body: { id: 123 } } as unknown as Request); // wrong type on purpose
之后:
import { fromAny } from "@total-typescript/shoehorn";
getUser(fromAny({ body: { id: 123 } }));
何时使用每个函数
| 函数 | 用例 | | --------------- | -------------------------------------------------- | | fromPartial() | 传递仍然通过类型检查的部分数据 | | fromAny() | 传递故意错误的数据(保留自动补全) | | fromExact() | 强制完整对象(之后可与 fromPartial 互换) |
工作流程
- 收集需求 - 询问用户:
- 哪些测试文件存在导致问题的
as断言? - 他们是否处理大型对象,其中只有某些属性重要?
- 他们是否需要传递故意错误的数据以进行错误测试?
- 安装并迁移:
- [ ] 安装:
npm i @total-typescript/shoehorn - [ ] 查找包含
as断言的测试文件:grep -r " as [A-Z]" --include="*.test.ts" --include="*.spec.ts" - [ ] 将
as Type替换为fromPartial() - [ ] 将
as unknown as Type替换为fromAny() - [ ] 添加来自
@total-typescript/shoehorn的导入 - [ ] 运行类型检查以验证