Search code examples
javascriptjasminekarma-jasminejasmine-jqueryjasmine2.0

How to fix function has already been spied on error in Jasmine


I have 3 tests, each testing various methods.

it('test function1', function() {
   spyOn(document, 'getElementById');
   // ... some code to test function1
   expect(document.getElementById).toHaveBeenCalled();

 });

it('test function2', function() {
   spyOn(document, 'getElementById');
   // ... some code to test function2
   expect(document.getElementById).toHaveBeenCalled();

 });

it('test function3', function() {
   spyOn(document, 'getElementById');
   // ... some code to test function3
   expect(document.getElementById).toHaveBeenCalled();    
 });

But when I run these tests I get the following error: getElementById has already been spied upon. Can someone explain why am I getting this error even when spies are in different test suites and how to fix it.


Solution

  • Once you spy on a method once, you cannot spy on it again. If all you want to do is check to see if it's been called in each test, just create the spy at the beginning of the test, and reset the calls in afterEach:

         spyOn(document, 'getElementById');
    
         afterEach(() => {
           document.getElementById.calls.reset();
         });
    
         it('test function1', function() {
           // ... some code to test function1
           expect(document.getElementById).toHaveBeenCalled();
    
         });
    
        it('test function2', function() {
           // ... some code to test function2
           expect(document.getElementById).toHaveBeenCalled();
    
         });
    
        it('test function3', function() {
           // ... some code to test function3
           expect(document.getElementById).toHaveBeenCalled();    
         });