Pierce through Javascript closures and access private symbols

Updated . Posted . Visible to the public.

If you are writing any amount of Javascript, you are probably using closures to hide local state, e.g. to have private methods.

In tests you may find it necessary to inspect a variable that is hidden behind a closure, or to mock a private method using Jasmine spies Show archive.org snapshot .

You can use the attached Knife helper to punch a hole into your closure, through which you can read, write or mock local symbols:

klass = (->

 privateVariable = 0

 privateMethod = ->
   privateVariable += 1

 publicMethod = ->
   privateMethod()

 add: add
 knife: eval(Knife.point)

)()

klass.knife.get('privateVariable') => 0
klass.knife.set('privateCounter', 5)
klass.knife.get('privateCounter') => 5
spy = klass.knife.mock('privateMethod').and.returnValue("mocked!")
klass.publicMethod() # => 'mocked!'
expect(spy).toHaveBeenCalled()

If you don't like Knife but have a similar use case you can also go thermonuclear with metafunction Show archive.org snapshot .

Henning Koch
Last edit
Henning Koch
Attachments
Keywords
spy, spies
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-07-29 17:31)