Is setting variables to null in afterEach preventing memory leaks?

Viewed 205

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

2 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 ;)

There is no advantage in this case, as you already concluded yourself, because JavaScript uses garbage collection.

  • For each test case you assign a new value to contact. The old value is no longer referenced and can be garbage collected.
  • At the end of the test suite the contact variable goes out of scope and its value can be garbage collected.
Related