Created
August 20, 2018 21:02
-
-
Save isner/e1b9d3ca15cb6fa7f39af6e873eee589 to your computer and use it in GitHub Desktop.
Mocking a function within a closure
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 `thirdPartyFunction` as a member of the imported module | |
| import * as myDependency from 'my-dependency' | |
| export default myTestableFunction(arg1) { | |
| // and call `thirdPartyFunction` as a member of the imported module | |
| myDependency.thirdPartyFunction(arg1) | |
| } |
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 { assert } from 'chai' | |
| import sinon from 'sinon' | |
| // import your testable module normally | |
| import myTestableFunction from './index' | |
| // import `thirdPartyFunction` as a member of the imported module | |
| import * as myDependency from 'my-dependency' | |
| describe('myTestableFunction', () => { | |
| let thirdPartySpy | |
| before(() => { | |
| // initialize the spy once | |
| thirdPartySpy = sinon.spy(myDependency, 'thirdPartyFunction') | |
| }) | |
| afterEach(() => { | |
| // reset it after each test | |
| thirdPartySpy.resetHistory() | |
| }) | |
| it('passes an argument to `thirdPartyFunction`', () => { | |
| myTestableFunction('foo') | |
| assert.isTrue(thirdPartySpy.calledWith('foo')) | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment