Skip to content

Instantly share code, notes, and snippets.

@kjs3 kjs3/module-testing.js
Last active Jul 6, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.