after brief romance revealing module pattern i've come realise set-back when comes unit-testing modules. cannot decide if approach testing module or whether there form of work-around.
consider following code:
var mywonderfulmodule = (function () { function publicmethoda (condition) { if(condition === 'b') { publicmethodb(); } } function publicmethodb () { // ... } return { methoda : publicmethoda, methodb : publicmethodb } }());
if wanted test (using jasmine) various paths leading through publicmethoda publicmethodb. might write small test so:
it("should make call publicmethodb when condition 'b'", function() { spyon(mywonderfulmodule , 'publicmethodb'); mywonderfulmodule.publicmethoda('b'); expect(mywonderfulmodule.publicmethodb).tohavebeencalled(); });
if understand correctly, there's copy of publicmethodb within closure cannot changed. if change mywonderfulmodule.publicmethodb afterwards:
mywonderfulmodule.publicmethodb = undefined;
calling mywonderfulmodule.publicmethoda
still run original version of b.
the example above of course simplified there plenty of scenarios can think of convenient unit test conditional paths through method.
is limitation of revealing module pattern or misuse of unit testing? if not work-arounds available me? i'm considering moving requirejs or reverting non-modular code.
any advice appreciated!
you cant test intern methodes of closure. , shouldn't spy on it. think about module black box. put in , out. should test thing out of module 1 expect.
spying on methodes in module makes not sense. think it. spy on it, test passes. change functionality creates bug, test still passes cause function still called never mention bug. if test thing cames out dont need spy on internal methodes cause, called implicite when outcome of module expect.
so in case there no thing goes in , nothing comes out. makes not sense believe module interacts dom or makes ajax call. things can test (dom) or should spy on (ajax).
you should make self familiar inversion of control , dependency injection. these patterns make modules more easier test.
Comments
Post a Comment