I recently switched from jasmine/istanbul to jest framework for my project jQuery Terminal and I’ve got coverage drop from 80-81% to about 69% with some update of the code and commented out code that I was working on.
So I thought it would be cool to highlight the lines that where covered and not covered by tests and since I use emacs as my editor I thought that I write a function that will do that.
Here it is:
(defun root-git-repo () (interactive) (replace-regexp-in-string "\n" "" (shell-command-to-string "git rev-parse --show-toplevel"))) (defun line-pos-at-line (line) (interactive) (save-excursion (goto-line line) (line-beginning-position))) (defun coverage-mark-buffer () (interactive) (let* ((dir (root-git-repo)) (json-object-type 'hash-table) (json-array-type 'list) (json-key-type 'string) (json (json-read-file (concat dir "/coverage/coverage-final.json"))) (filename (buffer-file-name (current-buffer))) (coverage (gethash filename json)) (statments (gethash "statementMap" coverage))) (save-excursion (maphash (lambda (key value) (let* ((statment (gethash key statments)) (start (gethash "start" statment)) (end (gethash "end" statment)) (start-line-pos (line-pos-at-line (gethash "line" start))) (start-pos (+ start-line-pos (gethash "column" start))) (end-line-pos (line-pos-at-line (gethash "line" start))) (end-pos (+ end-line-pos (gethash "column" end))) (color (if (= value 0) "dark red" "dark green")) (face `((t (:background ,color))))) (hlt-highlight-region start-pos end-pos face))) (gethash "s" coverage)))))
The function is using hlt-highlight-region from highlight.el by Drew Adams.
The function don’t check if coverage file exists. It assume that you’re opening from from git repo and that coverage file is in coverage directory (default for jest) in git root.
If you want to clear the buffer you can use this function:
(defun coverage-clear-buffer () (interactive) (save-excursion (end-of-buffer) (hlt-unhighlight-region 0 (point))))
Clear is much faster.
If you’re iterested in code coverage in Emacs you can take a look at jest-coverage minor mode that I’ve created based on this solution.