首页 > 解决方案 > 遍历 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。这是因为其中一些有额外的副作用,我没有包括上面的细节。

演示错误的操场

标签: typescriptjestjsgetter-setter

解决方案


推荐阅读