Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing javascript for a memory leak

Is there a way to unit test for javascript memory leaks? What I mean is, is there any way to access the heap directly from javascript code to check for detached DOM trees or increased memory usage?

I know you can do this from Chrome Dev Tools, but I'm wondering if there's a way to do it directly from my unit tests, since it seems tedious to write some code, take a heap snapshot, perform a potentially memory leaking operation, take another heap snapshot, and repeat for every single potentially memory leaking operation, every time a write another snippet of code. Not to mention that adding code in one place may cause an unexpected memory leak in another part of the application.

It's just that I wrote an application that had a huge memory leak, and I had to start from scratch. When I develop the application this time around, I want to make sure my unit tests can detect that I've just created a memory leak, and I can eliminate it as soon as possible.

I think I've seen tools like this for C++, but not for Javascript. Does anyone know of any? Thank you!

like image 718
Jacquerie Avatar asked Jul 21 '13 23:07

Jacquerie


2 Answers

According to MDN's docs on window.performance, Google Chrome has a non-standard extension (window.performance.memory) that gives access to values like usedJSHeapSize, totalJSHeapSize, jsHeapSizeLimit.

To get byte-level precision, you need to use the --enable-precise-memory-info flag.

For Garbage Collection, the only way I've found to force a browser to perform GC is with Chromium, with a special command flag. When you run this command:

chromium-browser --js-flags='--expose_gc'

you get access to the method window.gc(), which you can call to force GC.

This may open the possibility for testing memory usage in unit tests, for example.

like image 157
Matthias Avatar answered Oct 06 '22 14:10

Matthias


For Node.js there's leakage that can be used to perform memory related unit tests. If your test involves DOM, you may try using jsdom to simulate the browser behavior, but I cannot guarantee it will give you the same result.

like image 22
Mu-Tsun Tsai Avatar answered Oct 06 '22 14:10

Mu-Tsun Tsai