marchaos / jest-mock-extended

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

How to clear or reset all the mocked functions? #12

Closed cgfrost closed 4 years ago

cgfrost commented 4 years ago

Firstly, thanks for creating this, it's brilliant.

Before each of my tests I want to clear out my mocks but I can't find an easy way to do this. I could go function by function but this is messy when mocking a large interface. I know I could also just re-instantiate the mocked interface but that feels wrong. I imagine it takes time compared to just doing a mockReset() or mockClear() on each function.

Ideally, I'd like this, or similar.

    const mockUserService: UserService = mock<UserService>();
    let userController: UserController;

    beforeEach(() => {
        mockUserService.mock.mockReset();
        userController = new UserController(mockUserService);
    });
marchaos commented 4 years ago

Hey,

jest-mock-extended uses jest.fn() underneath the hood, so mockReset() or mockClear() should do as you would expect. I guess you're wanting to clear all methods that are mocked?

otherwise mockUserService.myMethod.mockReset() should work.

cgfrost commented 4 years ago

Hi.

Yes, mockUserService.myMethod.mockReset() is working perfectly. I'm looking for a lazy way to clear all the methods that are mocked in one go. I think it would need an extra property on MockProxy<T> but it's not obvious how to do this in a way that is consistent with the existing Jest APIs.

If you think it's a good idea and we can come up with a nice API for doing it I'm happy to put a pull request together.

Thanks for the quick response.

marchaos commented 4 years ago

Hey @cgfrost

I've created a PR with this functionality - https://github.com/marchaos/jest-mock-extended/pull/13. I had to use an external function to the mock just because of the way that TS and deep mocking works.

You should now be able to do:

import { mock, mockClear, mockReset } from 'jest-mock-extended';

describe('test' , () => {
    const mockUserService: UserService = mock<UserService>();
    let userController: UserController;

    beforeEach(() => {
        mockReset(mockUserService);
        userController = new UserController(mockUserService);
    });
});

This works with deep mocks too. There's some tests if you want to see it working. Are you able to try this branch before I merge into master?

marchaos commented 4 years ago

Merged and pushed 1.0.8 - see https://github.com/marchaos/jest-mock-extended/releases/tag/1.0.8