Skip to content

Instantly share code, notes, and snippets.

@isner
Created August 20, 2018 21:02
Show Gist options
  • Select an option

  • Save isner/e1b9d3ca15cb6fa7f39af6e873eee589 to your computer and use it in GitHub Desktop.

Select an option

Save isner/e1b9d3ca15cb6fa7f39af6e873eee589 to your computer and use it in GitHub Desktop.
Mocking a function within a closure
// 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)
}
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