Skip to content

Instantly share code, notes, and snippets.

@kjs3
Last active July 6, 2016 21:26
Show Gist options
  • Save kjs3/4c83bdaeddd7b2cacc38895292b07eb9 to your computer and use it in GitHub Desktop.
Save kjs3/4c83bdaeddd7b2cacc38895292b07eb9 to your computer and use it in GitHub Desktop.
Babel rewire and expect.js testing
// my-module.js
function privateFunc () {
console.log("Some convoluted logic.")
return 1 + 2
}
export default function () {
console.log("Hey! I'm the public interface for this module")
const importantNumber = privateFunc()
return importantNumber
}
// my-module-test.js
import expect from 'expect'
import myModule from './my-module'
// using a spy from the expect library
const privateFuncSpy = expect.createSpy().andReturn(10)
// privateFuncSpy is a function that can track how many times it was called and with what arguments
myModule.__Rewire__('privateFunc', privateFuncSpy)
// ^ using rewire along with a spy
describe('myModule', () => {
beforeEach(() => {
// It's a good idea to reset spys before each test
privateFuncSpy.reset()
})
it('calls privateFunc', () => {
expect(privateFuncSpy).toHaveBeenCalled()
// Yay!!!
})
it('returns whatever privateFunc returns', () => {
// I made privateFuncSpy return 10 so I can now expect that
expect(myModule()).toEqual(10)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment