When does Jasmine reset the spies?

27 views Asked by At

I have found this code:

describe('Test', function() {
  const NAVIGATOR = window.navigator;

  beforeEach(function() {
    spyOnProperty(window.navigator, 'userAgent').and.returnValue('Mozilla');
  })

  afterEach(function() {
    window.navigator = NAVIGATOR;
  });
}

Why is the code in afterEach needed? As far as I know, Jasmine resets spied-on functions after each spec with their normal implementation again. Looking in the docs also confirms that. So why is this needed? Is there something special here?

1

There are 1 answers

0
Rの卄IT On

You are right about that but Jasmine will automatically restore spied on functions after each test runs. So the afterEach rest here is likely redundant and not needed.

The key thig is the spyOnProperty is spying on the userAgent property of the navigator object. It is not replacing the entire navigator object.

So after each test, the userAgent property will be restored to it's original value automatically.

Resetting the entire navigatore object back to the original NAVIGATORconst is unnecessary.

A couple of things that may explain why it's there:

  • Might be incorrectly assumed Jasmine doesn't reset spied properties. So manually reset it just to be safe.
  • There may have been some specific issue or edge case with the testing framework/environment used that required manually resetting the navigator.
  • It was copy-pasted from somewhere else without understanding if it's needed.

But in general with Jasmine, you don't need to manually reset spied properties or functions in a afterEach. They will be handled automatically.

So In this case, the afterEach reset of navigator is likely redundant and can removed. The spied userAgent property will be restored correctly on its own after each test.


I hope this will help you. Cheers