jest
jest copied to clipboard
[Feature]: Improve mocking classes.
🚀 Feature Proposal
Make mocking classes with Jest painless by getting inspired from mockito.
Motivation
Currently you have jest.mock
with expects a path instead a class
, jest.fn
for single methods or jest.spyOn
also for methods. Which required a huge complex setup... I really like Jest. But mocking a class is everything else then "delightful" and in this particular case without focusing on "simplicity". (Jest quote).
Example
Currently I'm on Angular and want to test a Service with dependencies using TestBed
(Angular Testing Module).
I have to import a lot of services (deps) from a barrel file and mock every single method with e.g. jest.fn
...
Pitch
Using Mockito you just can use const myMock = mock(MyService)
(class not path) and then instance(myMock)
. And later in your tests, you can just set every method you want with when(myMock.getValue()).thenReturn(42)
. No need to define other methods. Just focus on that what you want to test. Don't care about the deeper dependencies.
To be honest, I've not jet found the a satisfying example with jest mocking. Either in relationship with Angular nor the Jest docs.
This issue is for considering and evaluating improving the mock system of the great testing framework Jest. Maybe I'm wrong or misinformed. But I wonder, would you agree that e.g. Mockito does it better? What's your opinion? I just could use mockito and I will do. But I wish it wasn't necessary.
Hi! For now, you might be satisfied with using jest-mock-extended. I already requested similar feature improvements (#11995) back in October 2021, but the issue has not gained any traction yet. Let's see how it goes. Currently, I am quite happy with jest-mock-extended.
Looks interesting, thanks for the hint. I see some parallels to Mockito. It's maybe something I'm looking for. I'll test it soon. Not sure if I finally use ts-mockito or jest-mock-extended. It would be great if Jest includes a more handy way to mock classes. Maybe by extending the existing mock. Passing the class object instead the path, etc. Now we have two libs for inspiration to make Jest even more "delightful".
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.
This issue was closed because it has been stalled for 30 days with no activity. Please open a new issue if the issue is still relevant, linking to this one.
This issue was closed because it has been stalled for 30 days with no activity. Please open a new issue if the issue is still relevant, linking to this one.
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.