marchaos / jest-mock-extended

Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
MIT License
853 stars 59 forks source link

No simple getter mocking planned yet? #84

Open Sebastriani opened 2 years ago

Sebastriani commented 2 years ago

It would be a nice feature to have since the solution proposed here #29 is kind of cumbersome...

krzysiekzabawa commented 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.

knicola commented 2 years ago

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

roblframpton commented 2 years ago

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).

krzysiekzabawa commented 1 year ago

@roblframpton , I stumbled upon exactly the same issue. As mentioned above - the only workaround is to use Object.defineProperty()

gusgorman2 commented 7 months ago

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

bjarketrux commented 2 months ago

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.