mardi 7 mai 2019

How to test a module with side effects?

Ignoring that it's bad, let's say I have a Javascript file which in normal operation is run in a particular context. This file:

  1. Expects some global variables to exist
  2. Defines some functions
  3. Calls some of its own functions
  4. Calls some of the functions found in the global namespace
  5. Modifies some of the global namespace's data

I want to set up some tests for the content of this file but am struggling.

I've tried:

  • Setting up a global context by throwing the expected things into global, then requiring the module, then checking the expected side effects have taken place. This works but I haven't figured out how to then change the global context and do it again, to make sure the output is as expected each time.
  • Requiring the module with rewire rather than require, so that I can monkey-patch some of its functions for further testing. This also works, but is still not ideal.

What strategies and frameworks may be helpful?

Is there any way to load the module and access/patch/test the functions it declares before the file's side effects execute?

Aucun commentaire:

Enregistrer un commentaire