Destroy Backbone.Router and all side effects after creating

Suppose you want to create an instance of Backbone.Router that calls Backbone.history.start, destroy all its traces, and create it again.

I need to do this for unit testing.

The problem is that creating a trunk router has global implications. Like Backbone.history, which is undefined until you do this.

var ReversibleRouter = Backbone.Router.extend({ initialize: function(){ _buildAppPaths(this.options) // Implementation not shown. Builds the application paths Backbone.history.start() }, destroy: function(){ // TODO: Implement this } }) 

I would like to be able to create and completely destroy so that I can do some unit testing in my implementation of the Router application.

Just call Backbone.history.stop() and set Backbone.history = undefined ?

+4
source share
2 answers

If you want to use more comprehensive types of stack integration, you can reset your application router using:

 Backbone.history.stop() Backbone.history = undefined // Could also probably use delete here :) 

It has been successful so far - our tests probably instantiate and kill the router 5 times during our qunit test. It works great.

It may be taunted as @AdamTerlson says this is the best way to go in the long run, but I'm still studying the philosophy of modulation and integration. I don't mind having a full stack test or two nonetheless.

+1
source

It may be a hoax, but I believe that you should be a mocking function outside of your functional unit, that your testing and it is especially important that your unit tests cannot get into the Live DOM, server or browser.

Check out SinonJS , this is great for that.

Here is an example of testing the initialization method of the router without affecting the state of the browser history.

 test('...', function () { // Arrange var buildAppPaths = sinon.stub(ReversibleRouter.prototype, '_buildAppPaths'); var startHistory = sinon.stub(Backbone.history, 'start'); var options = {}; // Act new ReversibleRouter(options); // Assert ok(buildAppPaths.calledWith(options)); ok(startHistory.calledOnce); // or ok(Backbone.history.start.calledOnce); }); 

With this approach, you successfully claim that all calls were made to external blocks of functionality, including parameters. At this point, you can believe that the external call will do its job (verified by additional unit tests).

To make calls outside this single unit, integration tests will be run, not unit tests.

0
source

All Articles