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

10,082

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();    
     });
Share:
10,082
Mumzee
Author by

Mumzee

I have been working on client side scripting for quite a while now. It fascinates me that how simple, beautiful and powerful JavaScript is.

Updated on June 14, 2022

Comments

  • Mumzee
    Mumzee almost 2 years

    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.

    • FiniteLooper
      FiniteLooper about 5 years
      Why are you spying on and testing native JS/browser code? I think it's safe to expect that these functions will work when they are called.
    • Mumzee
      Mumzee about 5 years
      Because test does not load the HTML file, so document.getElementById('').style etc in js file will throw error.
    • FiniteLooper
      FiniteLooper about 5 years
      You should probably instead test for the existence of a certain element rather than testing that native browser code was called or not.
  • Yuri
    Yuri over 3 years
    Just to clarify, you can spy on a method of a single object only once.