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.