Вопрос

We have an immediate function in the file 'mediator.js' which adds a 'mediator' object to the global namespace. This 'mediator' is the only global object we have.

Now we have many different unit-tests for the 'mediator' object. And we want each test to run in isolation - in other words, each test needs to start by invoking the immediate function to create a new clean mediator object.

The tests are written in Jasmine and we run them with both Chutzpah and JsTestDriver.

So how can I do this?

  • In Chutzpah, I could put each individual test into it's own js file, and reference mediator.js in each test file
  • With JsTestDriver, I could need a config file for each test, which includes the mediator.js and the test file

We are also considering abandoning the immediate pattern, and have a constructor function to create a Mediator object. This would be a shame, because in production code we only need to create the mediator once, and don't want to have the constructor function hanging around polluting the global namespace.

Surely other people have encountered this problem when testing immediate / self-involking / self-executing functions´. So what is 'best-practice'?

Это было полезно?

Решение

I think exposing the mediator constructor and having each test override the existing global member might be the best option. Exposing one object constructor would be a big issue. It sounds like the work-arounds are a lot more effort than just exposing on method.

Something like:

// mediator.js

function createMediator(){ ... }

window.mediator = createMediator();



// In unit test

beforeEach(function () {
  window.mediator = createMediator();
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top