Question

I'm using the revealing pattern and initial class instantation in my JavaScript. I am also using Jasmine to test this class, but need a way to reset the state of the myNamespace.myViewModel (this is a simple example, but imagine a complex view model with multiple variables) before each test is run.

Here's an example class:

myNamespace.myViewModel = (function(ko, $, window){
   var init = function(){},
       name = 'bob',
       nameSetter = function(value){ name = value; };
   return {
     Init: init,
     Name: name,
     NameSetter: nameSetter
   };
}(ko, $, window));

In Jasmine I start out with:

describe("VM Specs", function () {
    'use strict';
    var vm;
    beforeEach(function(){
       // the vm isn't re-created since it is a "static" class in memory
       vm = myNameSpace.myViewModel;
    });
    it("should set name", function(){
       vm.NameSetter('joe');
       expect(vm.Name === 'joe').toBeTruthy();
    });
    it("should have the default state, even after the other test ran", function(){
       expect(vm.Name === 'bob').toBeTruthy();
    });
});

Is there a way to do this?

Was it helpful?

Solution

You can't. Cause all that the pattern does, is to create a new object that has some variables bound in a closure. So even if you use this in your app you cant relay on the state of this object cause you cant create a new version of it. Also the word class isn't describing this pattern right as you can't create new instances from it. So you should ask yourself if this is the right pattern for you in this case.

OTHER TIPS

There is an afterEach() function. Works the same as beforeEach() but after the tests are run:

afterEach(function(){
    //reset the state here!
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top