Ali Khan
Ali Khan

Reputation: 134

Is it possible to clear the mock of a module in JEST?

I want to mock the function forgotPassword inside the module authenticationPlugin/App, So i am doing this

jest.mock("authenticationPlugin/App", () => ({
    forgotPassword (email: string) {
        const msg='success'
        email='a'
        return msg
    }
}))

Now i want to clear the mock of authenticationPlugin/App and have a different implementation for the forgotPassword method

So i did this

jest.clearAllMocks();
jest.mock("authenticationPlugin/App", () => ({
        forgotPassword (email: string) {
            throw new Error(<any>{'err':{'message':'Network Error'}})
        }
    }))

Now i expect the forgotPassword method to have a different implementation after clearing the mocks in for the module authenticationPlugin/App but it doesn't change...

Upvotes: 0

Views: 83

Answers (1)

mgarcia
mgarcia

Reputation: 6325

If you want to have a different implementation for the mock in each test, you can use jest.fn instead.

Expanding on your code, it could look like this:

it('returns success', () => {
    authApp.forgotPassword = jest.fn((email: string) => {
        const msg='success'
        email='a'
        return msg
    });

    // Your test code here.
});

test('returns error', () => {
    authApp.forgotPassword = jest.fn((email: string) => {
        throw new Error(<any>{'err':{'message':'Network Error'}})
    });

    // Your test code here.
});

Upvotes: 1

Related Questions