Last active
August 14, 2020 18:34
-
-
Save iturgeon/882431b1fdbab1e8f2c7a59eb9ce250c to your computer and use it in GitHub Desktop.
Jest Test Exercise - Unreachable internal variables
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 Dispatcher from './dispatcher' | |
// scoped to this file, not accessable outside | |
// used in the real world to prevent sending a | |
// window close tracking api request twice | |
let closeNowTriggered = false | |
const dispatchCloseNow = () => { | |
if (!closeNowTriggered) { | |
Dispatcher.trigger('window:closeNow') | |
// prevent the trigger from being called twice | |
// because the window is closing, it never | |
// needs to be set back to false. | |
closeNowTriggered = true | |
} | |
} | |
export default dispatchCloseNow |
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 Dispatcher from './dispatcher' | |
import dispatchCloseNow from './dispatch-close-now') | |
jest.mock('./dispatcher', () => ({ | |
trigger: jest.fn() | |
})) | |
describe('Close Window Dispatcher', () => { | |
test('dispatchCloseNow triggers window:closeNow', () => { | |
// execute | |
dispatchCloseNow() | |
// verify | |
expect(Dispatcher.trigger).toHaveBeenCalledWith('window:closeNow') | |
expect(Dispatcher.trigger).toHaveBeenCalledTimes(1) | |
}) | |
test('dispatchCloseNow only calls window:closeNow once', () => { | |
// execute | |
dispatchCloseNow() | |
dispatchCloseNow() | |
// verify | |
expect(Dispatcher.trigger).toHaveBeenCalledWith('window:closeNow') | |
expect(Dispatcher.trigger).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
const Dispatcher = { | |
trigger: eventName => { | |
// simplified for sake of this example | |
console.log(`${eventName} triggered!`) | |
} | |
} | |
export default Dispatcher |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment