0

I want to test the getters/setters on a JavaScript class I've written. I'm testing my code with Jest. For brevity I'm attempting to use the test.each() API provided by Jest.

Here's what I have so far.

The class:

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;
  }
}

And a test:

// 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 gives me the error:

Cannot assign to 'readOnlyProp' because it is a read-only property

Quite right!

What I want to do is filter just the writable properties (either programmatically or hard-coded), and then just test those. Is it possible to adapt the hasKey function somehow to accommodate this?

P.S. You might wonder why I'm testing getters / setters. It's because some of them have extra side effects that I haven't included the detail of above.

Playground demonstrating the error.

Jared Smith
  • 19,721
  • 5
  • 45
  • 83
jayp
  • 675
  • 6
  • 21
  • 1
    [Object.getOwnPropertyDescriptors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors) – Jared Smith Feb 27 '20 at 19:15
  • I've been experimenting with Object.getOwnPropertyDescriptors that doesn't seem to do the trick. – jayp Feb 27 '20 at 22:01
  • It does indeed: `Object.entries(Object.getOwnPropertyDescriptors(obj)).forEach(([name, desc]) => desc.writable && console.log(name));` If that does not answer your question, then you need to edit your question to clarify what you're after. – Jared Smith Feb 27 '20 at 22:11
  • I'm specifically trying to address that TypeScript error in the question. Adding the extra check with getOwnPropertyDescriptors works in theory yes but TypeScript compiler still gives the same error message – jayp Feb 28 '20 at 00:39

0 Answers0