Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is setting variables to null in afterEach preventing memory leaks?

I'm reading the book Testing Angular Applications, which suggests to reset variables to null in the afterEach calls. The accompanying text says:

You can use the teardown part of the test to make sure instances of variables get destroyed, which helps you avoid memory leaks. In this case, you'll use the afterEach function to set the contact variable to null.

Isn't the the used memory freed when the next beforeEach sets a new value or at the end of the whole suite when the describe call is finished? What's the advantage if any of this explicit teardown?

import ContactClass from './contact';

describe('Contact class tests', () => {
  let contact: ContactClass = null;
  
  beforeEach(() => {
    contact = new ContactClass();
  });
  
  it('should have a valid constructor', () => {
    expect(contact).not.toBeNull();
  });
  
  afterEach(() => {
    contact = null;
  });
});

I don't such a teardown in Angular's testing guide either: https://angular.io/guide/testing-services

like image 688
kossmoboleat Avatar asked Oct 14 '25 08:10

kossmoboleat


1 Answers

This is a jasmine issue. It holds an internal reference to everything which is specified outside of the it() blocks. In your case this is contact. This reference cannot be cleaned up by your browser and therefore not getting garbage collected.

Here is a blogpost dealing with the problem.

Offtopic: Greetings from a former colleague ;)

like image 101
DonJuwe Avatar answered Oct 18 '25 03:10

DonJuwe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!