Mumzee
Mumzee

Reputation: 808

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.

Upvotes: 12

Views: 38926

Answers (2)

kaustubh badamikar
kaustubh badamikar

Reputation: 672

Its late to reply but, if someone is trying to spyon same function multiple times but with different return value you could use

it('test function', function() {
   // spy and return data
   spyOn(serviceName,'functionName').and.returnValue(data);
   expect(serviceName.functionName).toHaveBeenCalled();
   
   // spy and return newData
   serviceName.functionName = jasmine.createSpy().and.returnValue(newData);
   expect(serviceName.functionName).toHaveBeenCalled();
});

Upvotes: 13

Adam Jenkins
Adam Jenkins

Reputation: 55792

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();    
     });

Upvotes: 7

Related Questions