Why is it useful
Enabling Code Coverage
Code coverage is measured on a Coverage tab in Developer Tools. To open Dev Tools press ⌘+⌥+I (Mac) or Control+Shift+I (Windows, Linux). After this, you can access the Coverage from the Command Menu:⌘+⇧+P (Mac) or Ctrl+Shift+P (Windows, Linux) and then typing Show Coverage.
Alternatively, you can show the Coverage tab from Dev Tools menu by choosing More tools → Coverage.
When you manage to open the coverage tab, it will look like this:
Capturing Code Coverage
After opening the Coverage tab, you just need to press the record button (Instrument Coverage). Then you start to execute the desired use case. That is – you start to navigate the application, click buttons, fill forms and such. When you are finished you just press the button again to stop recording and show the coverage results. This is an example of coverage results from browsing stackoverflow.com:
As you can see the table shows all the JS and CSS files which were downloaded during my session there. Each file contains information how big portion of the file was actually used in my session – both as percentage and size in bytes. On the very bottom in the status bar, there is a summary. You can tell that whole 83% was not used, that is 795 KB.
This is a nice overview, but you can actually display a per-line report of each of these files by double-clicking a row in the summary table:
Green lines mean that the code on the line was executed fully, red lines were not used during the recording session at all. Red/green lines were executed partially – only some fraction of the code was used, but not all.
When using the coverage feature you need to be careful not to jump to conclusions too quickly. Coverage data shown is gathered dynamically based on your behavior and actions in your application. That means it is gathered and computed only based on actions you actually performed during your recorded session. Many elements on the page are usually rendered dynamically only under certain conditions. Some of them may be rendered only in certain corner cases which rarely occur and which you did not encounter while recording the session. Such code would be marked as unused, but you cannot really remove it as it would be missing in some scenarios. Always be careful when removing portions of code that you consider unused as it always does not have to be the case.