total-typescript/shoehorn
GitHub: total-typescript/shoehorn
一个 TypeScript 测试辅助库,帮助开发者在单元测试中安全、便捷地传入部分模拟数据,同时保持类型检查和自动补全能力。
Stars: 568 | Forks: 11
# shoehorn
```
npm i @total-typescript/shoehorn
```
`shoehorn`(意为“强行塞入空间”)能让你在测试中**传入部分数据**,同时让 TypeScript 保持满意。
### 问题
在测试中使用 `as` 让人感觉很糟。
```
type Request = {
body: {
id: string;
};
// Imagine oodles of other properties...
};
it("Should get the user", () => {
// Even though we only care about body.id for
// this test, we need to pass in the whole Request
// object
getUser({
body: {
id: "123",
},
} as Request);
});
```
- 你被教导不要使用它
- 你需要_手动_指定想要断言的类型
- 为了用不正确的数据进行测试,你需要进行“双重断言”(`as unknown as User`)
### 解决方案
`shoehorn` 为你提供了一些一流的原始方法,用于_安全地_向测试提供不完整的数据。
```
import { fromPartial } from "@total-typescript/shoehorn";
it("Should get the user", () => {
getUser(
fromPartial({
body: {
id: "123",
},
}),
);
});
```
### 但是向测试传入部分数据不好吗?
一般来说是的。必须在测试中传入巨大的对象,表明你的类型设计得太松散了。理想情况下,每个函数应该只声明它需要的数据。
不幸的是,我们生活在现实世界中。在很多情况下,`shoehorn` 是最佳选择:
- **遗留代码库**:如果你正在开发一个庞大的代码库,你可能没有时间去重构一切以达到完美。
- **第三方库**:如果你在使用第三方库,你可能无法在不添加无用包装函数的情况下更改其类型。
## API
对于下面的每个示例,假设定义了以下类型:
```
type Request = {
body: {
id: string;
};
// Imagine oodles of other properties...
};
// The function we're testing
const requiresRequest = (request: Request) => {};
```
### fromPartial
允许你向期望某种类型的参数位置传入一个深度部分类型。
```
import { fromPartial } from "@total-typescript/shoehorn";
requiresRequest(
fromPartial({
body: {
id: "123",
},
}),
);
```
如果你传入的类型与期望的类型不匹配,它将报错:
```
// Type "1234123" has no properties in common
// with type 'PartialObjectDeep'
requiresRequest(fromPartial("1234123"));
```
### fromAny
允许你向参数位置传入任何内容,同时仍然为你提供原始类型的自动补全:
```
import { fromAny } from "@total-typescript/shoehorn";
requiresRequest(
fromAny({
body: {
id: 124123,
},
}),
);
```
如果你传入的内容不匹配,它也不会报错。
```
// All good!
requiresRequest(fromAny("1234123"));
```
### fromExact
一种便捷方法,强制你传入某个类型的所有属性。适用于你想与 `fromPartial`/`fromAny` 灵活切换的场景:
```
import { fromExact } from "@total-typescript/shoehorn";
requiresRequest(
// Will fail! We're not passing all the oodles of
// properties of Request
fromExact({
body: {
id: 124123,
},
}),
);
```
标签:CMS安全, DNS解析, JavaScript, Mock测试, NPM包, OSV-Scalibr, TypeScript, 单元测试, 安全插件, 开源项目, 暗色界面, 测试工具, 类型安全, 自动化攻击, 遗留代码重构, 部分Mock