typescript - 遍历 TypeScript 中指定的 getter / setter
问题描述
我想在我编写的 JavaScript 类上测试 getter/setter。我正在用 Jest 测试我的代码。为简洁起见,我尝试使用test.each()
Jest 提供的 API。
这是我到目前为止所拥有的。
班上:
class MyClass {
private _propName: string
private _readOnlyProp: string
get readOnlyProp() {
return this._readOnlyProp;
}
set propName(v: string) {
this._propName = v;
}
get propName() {
return this._propName;
}
}
和一个测试:
// credit https://stackoverflow.com/a/56569217/675177
function hasKey<O>(obj: O, key: keyof any): key is keyof O {
return key in obj;
}
test.each([
['propName', 'testValue'],
])('can get/set %s', (prop, value) => {
const m = new MyClass();
if (hasKey(m, prop)) {
expect(m[prop]).toBeUndefined();
m[prop] = value; // <= error!
expect(m[prop]).toEqual(value);
}
});
TypeScript 给了我错误:
Cannot assign to 'readOnlyProp' because it is a read-only property
非常正确!
我想要做的是只过滤可写属性(以编程方式或硬编码),然后只测试它们。是否有可能以某种方式调整 hasKey 函数以适应这种情况?
PS 你可能想知道我为什么要测试 getter / setter。这是因为其中一些有额外的副作用,我没有包括上面的细节。
解决方案
推荐阅读
- node.js - Mongodb:我可以比较一个字段中的值是否包含在另一个字段中
- javascript - SyntaxError:位置 1 curl 请求的 JSON 中的意外标记 u
- npm - 无法在 windows10x64 上使用 NPM 安装“node-red-contrib-tf-model”
- android - 从 S3 读取数据以用于移动应用程序 - 仅允许特定域
- typescript - 如何在 TypeScript 中一起使用 for .. of 和 Object.entries
- python - 数组的所有排列,其中数组中的每个元素必须按 0 和 n 之间的范围增加
- webkit - 带有 Face ID 和 Touch ID 的 Webauthn
- scala - 通过 SparkStructedStreaming 连接到 ActiveMq 时出现 MqttException
- python - 如何使用 python 在 psql 数据库中创建一个表?
- c - 未能合并文件 /usr/lib/libc_nonshared.a(elf-init.oS) 的目标特定数据