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?
You are right about that but
Jasminewill automatically restore spied on functions after each test runs. So theafterEachrest here is likely redundant and not needed.The key thig is the
spyOnPropertyis spying on theuserAgentproperty of thenavigatorobject. It is not replacing the entirenavigatorobject.So after each test, the
userAgentproperty will be restored to it's original value automatically.Resetting the entire
navigatoreobject back to the originalNAVIGATORconst is unnecessary.A couple of things that may explain why it's there:
But in general with
Jasmine, you don't need to manually reset spied properties or functions in aafterEach. They will be handled automatically.So In this case, the
afterEachreset ofnavigatoris likely redundant and can removed. The spieduserAgentproperty will be restored correctly on its own after each test.I hope this will help you. Cheers