Last active
April 7, 2021 22:27
-
-
Save ninetails/a8b8c7ed57973c088c9ad58a50f96ffd to your computer and use it in GitHub Desktop.
mockar função dentro de chamada de modulo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fn from "./index"; | |
import module from './module'; | |
jest.mock("./module", () => { | |
const mod = jest.requireActual('./module').default; | |
const mocked = () => { | |
const moduleInstance = mod(); | |
mocked.lastMockedOnClick = jest.spyOn(moduleInstance, 'onClick'); | |
mocked.lastMockedOnEvent = jest.spyOn(moduleInstance, 'onEvent'); | |
return moduleInstance; | |
}; | |
return mocked; | |
}); | |
afterEach(jest.clearAllMocks); | |
afterAll(jest.restoreAllMocks); | |
test("sem mockar eventos", () => { | |
fn(); | |
expect(module.lastMockedOnClick).toHaveBeenCalledTimes(1); | |
expect(module.lastMockedOnEvent).toHaveBeenCalledTimes(1); | |
}); | |
test("mockando eventos", () => { | |
module.lastMockedOnClick.mockImplementation(() => console.log('mocked onClick')); | |
module.lastMockedOnEvent.mockImplementation(() => console.log('mocked onEvent')); | |
fn(); | |
expect(module.lastMockedOnClick).toHaveBeenCalledTimes(1); | |
expect(module.lastMockedOnEvent).toHaveBeenCalledTimes(1); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fn from "./index"; | |
import module from './module'; | |
jest.mock("./module", () => { | |
const mocked = () => ({ | |
onClick: () => { | |
mocked.lastOnClickCalled = jest.fn(() => console.log('mocked onClick')); | |
return mocked.lastOnClickCalled(); | |
}, | |
onEvent: () => { | |
mocked.lastOnEventCalled = jest.fn(() => console.log('mocked onEvent')); | |
return mocked.lastOnEventCalled(); | |
}, | |
}); | |
return mocked; | |
}); | |
afterEach(jest.clearAllMocks); | |
afterAll(jest.restoreAllMocks); | |
test("...", () => { | |
fn(); | |
expect(module.lastOnClickCalled).toHaveBeenCalled(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment