Open Sebastriani opened 2 years ago
I would like to second on that.
The library is very neat to use, however mocking getters using Object.defineProperty()
is simply yuk :( It looks more like ugly hack rather than good default way of dealing with things.
the built-in spyOn()
method is now able to mock getters / setters ie. jest.spyOn(video, 'play', 'get')
https://jestjs.io/docs/jest-object#jestspyonobject-methodname-accesstype
the built-in
spyOn()
method is now able to mock getters / setters ie.jest.spyOn(video, 'play', 'get')
Could you expand on that a little? I thought you meant I could do something like this:
const req = mock<Request>();
const params = jest.spyOn(req, "params", "get");
But that gives me the error "params property does not exist" (which is definitely not true - it's there, and it's a getter).
@roblframpton , I stumbled upon exactly the same issue. As mentioned above - the only workaround is to use Object.defineProperty()
I also get a runtime error :
Error: Property
foo
does not exist in the provided object
Would be really good for Jest mock extended to allow you to mock properties. Its a big missing feature atm
The suggested work around to use Object.defineProperty
is really ugly and cumbersome
How about something like this:
interface Strings {
readonly size: number;
item(index: number): string;
}
const mockStrings = mock<Strings>({ size: 0 });
jest.replaceProperty(mockStrings , 'size', 6);
In this case I not sure you need the jest.replaceProperty call, but I had a property that returned an object and this worked (as the object would otherwise be a proxy.
It would be a nice feature to have since the solution proposed here #29 is kind of cumbersome...