How to reset service between tests in AngularJS

I have a service that is injected into a beforeEach:

beforeEach(inject(function($rootScope, $state, $injector, $controller, MyService) {
    var state = $state;
    scope = $rootScope.$new();
    myService = MyService;
    ctrl = $controller('MainCtrl', {$state: state, MyService: myService});
}));

      

And I have some tests described in "it":

it('test1', function() { 
   var data = ["test"]; 
   ctrl.extract_data(data); 
   expect(myService.get_data()).toEquals("test");
});

      

Now my problem is that I have a shared variable in the service (variable data) between tests and if I run a test with different data (eg var data = ["a", "b"]) the variable that is shared in myService, will contain a, b and test (which was obtained from the previous test). Is there a way to "reset" the content of the service every time I run a test?

+3


source to share


1 answer


I don't know the path to reset, but each block it

has nothing to do with the other blocks it

. You can simply introduce a new controller to each block it

.



it('test1', function() {
   var ctrl; 
   var data = ["test"]; 
   inject(function($controller) {
     ctrl = $controller('MainCtrl', {$state: state, MyService: myService}
   })
   ctrl.extract_data(data); 
   expect(myService.get_data()).toEquals("test");
});

      

0


source







All Articles