• Stars
    star
    248
  • Rank 163,560 (Top 4 %)
  • Language
    JavaScript
  • Created over 8 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[deprecated; use babel-plugin-istanbul instead] Istanbul-compatible code coverage instrumentation plugin for Babel.

UNMAINTAINED

This Babel plugin is not maintained anymore, sorry.

Please consider checking out babel-plugin-istanbul.

Feel free to keep using this plugin if you have difficulty migrating to other solutions, but please keep in mind that no new versions will be published.

--

babel-plugin-__coverage__

npm version npm downloads Build Status codecov.io MIT Licensed

A Babel plugin that instruments your code with __coverage__ variable. The resulting __coverage__ object is compatible with Istanbul, which means it can instantly be used with karma-coverage and mocha on Node.js (through nyc).

Note: This plugin does not generate any report or save any data to any file; it only adds instrumenting code to your JavaScript source code. To integrate with testing tools, please see the Integrations section.

News: For nyc users, v11.0.0 is a breaking change from v1.11.111. See release notes for more details.

Usage

Install it:

npm install --save-dev babel-plugin-__coverage__

Add it to .babelrc in test mode:

{
  "env": {
    "test": {
      "plugins": [ "__coverage__" ]
    }
  }
}

Integrations

karma

It just works with Karma. First, make sure that the code is already transpiled by Babel (either using karma-babel-preprocessor, karma-webpack, or karma-browserify). Then, simply set up karma-coverage according to the docs, but don’t add the coverage preprocessor. This plugin has already instrumented your code, and Karma should pick it up automatically.

It has been tested with bemusic/bemuse project, which contains ~2400 statements.

mocha on node.js (through nyc)

Configure Mocha to transpile JavaScript code using Babel, then you can run your tests with nyc, which will collect all the coverage report.

babel-plugin-__coverage__ respects the include/exclude configuration options from nyc, but you also need to configure NYC not to instrument your code by adding these settings in your package.json:

  "nyc": {
    "sourceMap": false,
    "instrument": false
  },

Ignoring files

You don't want to cover your test files as this will skew your coverage results. You can configure this by configuring the plugin like so:

"plugins": [ [ "__coverage__", { "ignore": "test/" } ] ]

Where ignore is a glob pattern.

Alternatively, you can specify only which will take precedence over ignore:

"plugins": [ [ "__coverage__", { "only": "src/" } ] ]

Canned Answers

There’s already Isparta. Why another coverage tool?

Note: Some text in this section is outdated and I say this instead of keeping this section up-to-date lol. So Isparta is now unmaintained and a new version of Istanbul that supports arbitrary compile-to-JS language is coming…

Isparta is currently the de-facto tool for measuring coverage against ES6 code, which extends Istanbul with ES6 support through Babel. It works very well so far, but then I hit some walls with it.

So I’ve been trying to get webpack 2 to work with Istanbul/Isparta. To benefit from webpack 2’s with tree shaking, I need to keep import and export statements in my ES6 modules intact. However, with this setup I can’t get code coverage to work. Inspecting Isparta’s source code reveals how it works:

  1. It uses Babel to transpile ES6 back into ES5, saving the source map.
  2. It uses Istanbul to instrument the transpiled source code. This produces some initial metadata (in a global variable called __coverage__) which contains the location of each statement, branch, and function. Unfortunately, these mapings are mapped to the transpiled code. Therefore,
  3. The metadata is processed using source map obtained from step 1 to map the location in transpiled code back to the location in the original source code.
  4. The final instrumented code in ES5 is generated. This code shouldn’t be processed through Babel again, or it will be redundant and leads to slower builds.

Since transforming import/export statements has now been disabled, instrumentation now dies at step 2, because the Esprima that Istanbul is using cannot process import/export statements.

So I looked for something else, and I found babel-plugin-transform-adana. I tried it out immediately. It turns out that although adana also generates the __coverage__ variable, it uses its own format which is not compatible with most existing tools (e.g. istanbul’s reporter, karma-coverage and nyc). Tools need to be reinvented for each test harness.

So I went back to use webpack 1 for the time being.

Now, with lots of tools to help developers author Babel 6 plugins, such as the Babel Handbook and the AST Explorer, it’s not that hard to create Babel plugins today. So I gave it a shot. This is my first Babel plugin.

It turns out that I can create a rudimentary instrumenter with Babel 6 in roughly 300 LOC (compare to Istanbul’s instrumenter which has ~1,000 LOC). Babel has A LOT of cool stuff to make transpilation easy, from babel-template to babel-traverse to babel-helper-function-name. Babel’s convenient API also handles a lot of edge cases automatically. For example, if a function begins with 'use strict' statement, prepending a statement into its body will insert it after the 'use strict' statement. It also transparently converts if (a) b into if (a) { b } if I want to insert another statement before or after b.

I haven’t tested this with webpack 2 yet.

Is it stable?

Well, I wrote most of it in two nights and have only tested some basic stuffs. So speaking in terms of maturity, this one is very new.

However, I tried using this in some bigger projects, such as bemusic/bemuse (which contains around 2400 statements). It works, with only few problems (which have now been fixed), and now it works fine.

Note: If you’re using babel-plugin-__coverage__ inside a larger-scale application, feel free to send pull request and update this section kthx!

Is the resulting coverage differ from Istanbul/Isparta?

Sometimes there’s so much logic in a single statement (usually due to functional programming techniques), it is very likely that not every part of a statement will be covered by tests (see picture below). Since most coverage service only cares about statement coverage, and I want coverage numbers to be very frank, babel-plugin-__coverage__ will treat certain expressions as statements.

Most likely, this means if you switch to this plugin your coverage percentage will most likely go down compared to when you were using Istanbul or Isparta. But if you use a lot of arrow functions, this means your coverage will be more accurate! Here’s an example from the bemusic/bemuse project:

Imgur

Here are some notable differences:

  1. Arrow function expression body is treated as a statement, because its body may never be evaluated.

       const x = a => b => c => a + b + c
    // <--------------------------------> S1
    //                <-----------------> S2
    //                     <------------> S3
    //                          <-------> S4
  2. Logical operator’s right hand side expression is treated as a statement, because it may be short-circuited.

       const value = a + b || a - b
    // <--------------------------> S1
    //                        <---> S2
  3. Each of conditional operator’s branch is treated as a statement because it may not be evaluated.

       const value = op === 'add' ? a + b : a - b
    // <----------------------------------------> S1
    //                              <---> S2
    //                                      <---> S3
  4. Default parameters and values for destructuring are treated as a statement, because the default may not be evaluated.

       function setValue (newValue = defaultValue) { }
    //                                             <-> S1
    //                               <----------> S2

How do I ignore branches/statements?

I haven’t implemented it. I once posted an issue on Isparta asking about ignoring statements in Isparta (which is now fixed). But nowadays I just think that “coverage is just a number,” so I don’t need them anymore. If you want it, pull requests are welcome!

More Repositories

1

ttycast

Broadcast your tty to the world! Stream your live terminal session online. Powered by ttyrec, tty.js and Socket.IO
JavaScript
431
star
2

YosemiteAndElCapitanSystemFontPatcher

Change the system font of Mac OS X Yosemite.
AppleScript
347
star
3

promptpay-qr

🏦 Mobile web app (https://promptpay2.me), command line app, and JavaScript library to generate QR Code payload for PromptPay.
JavaScript
222
star
4

todo-actions

Turn TODO in source code into issues and close them when they are gone. Runs on GitHub Actions.
TypeScript
194
star
5

automatron

Personal LINE bot to automate various tasks. Home automation, expense tracking, transaction monitoring
TypeScript
155
star
6

html5-animation-video-renderer

Render HTML5-based animation into a high-quality video. (Tested with 1080p60)
JavaScript
148
star
7

github-actions-docker-layer-caching-poc

Dockerfile
91
star
8

synchroscope

Realtime Angular.js scope syncing across multiple clients with Socket.IO
JavaScript
86
star
9

pushnot

Personal Push Notification Server
JavaScript
71
star
10

WebMIDICon

🎹🥁 My MIDI instruments!
TypeScript
69
star
11

ThreadGPT

Alternative frontend to ChatGPT (gpt-3.5-turbo / gpt-4) with a thread-based interface
TypeScript
65
star
12

prettier-standard-formatter

JavaScript
61
star
13

sheet.spacet.me

Quickly turn a Google Sheets spreadsheet into a public, CDN-backed JSON endpoint.
HTML
59
star
14

fiery

🔥 Easy declarative modern Firebase binding for React ^_^
TypeScript
58
star
15

it.js

Chainable object-oriented functional combinators
JavaScript
58
star
16

tailwind-search

Having trouble memorizing all the utility classes in Tailwind? Remember the CSS code, but did not remember which is the corresponding Tailwind CSS utility class? Search for it here!
CSS
43
star
17

hide-stack-frames-from

Filter stack trace by npm package name.
JavaScript
42
star
18

i2DX

Web-based IIDX controller for iPad / iPhone / Android (with Opera Mobile) (with server for Mac / Windows)
JavaScript
41
star
19

pixelpaint

An example for my upcoming Medium article..........
HTML
40
star
20

headless-terminal

Headless xterm emulator in JavaScript, forked from tty.js's term.js.
JavaScript
34
star
21

dark-facebook

[UNMAINTAINED] A dark theme for Facebook. Available as a Stylish user skin and a custom theme in Social Fixer for Facebook.
CSS
34
star
22

remark-lint-thai

เครื่องมือโอเพนซอร์ซสำหรับตรวจสอบข้อความภาษาไทยเบื้องต้น
JavaScript
31
star
23

transcribe

CLI tool for macOS that transcribes speech from the microphone using Apple’s speech recognition API, SFSpeechRecognizer. (help.)
Swift
29
star
24

atom-import-sf-mono

Use the SF Mono font in Atom by importing it from Terminal.app
CSS
29
star
25

ride

Simple and beautiful monkey-patching library for JavaScript.
TypeScript
26
star
26

timelapse

Capture a timelapse screenshot of my projects using GitHub Actions.
JavaScript
26
star
27

auden

Audience engagement platform
TypeScript
24
star
28

blurhash-image

HTML custom element for Blurhash image
TypeScript
24
star
29

setup-github-actions-caching-for-turbo

Action to set up Turborepo Remote Caching to work with GitHub Actions' built-in cache instead of Vercel (codename: turbogha)
TypeScript
24
star
30

vxcli

A simple CLI application that listens to your voice, converts it to text, and copies it to your clipboard, powered by Google Cloud Speech-To-Text API.
JavaScript
23
star
31

personal-puppeteer

A personal web page screenshotting service. Basically, it exposes an API that I can use to generate screenshot of any URL.
TypeScript
23
star
32

ticket-checkin

Ticket check-in system, for events
TypeScript
22
star
33

mosh-static

Static builds of mosh-server
Dockerfile
22
star
34

FocusHighlight.spoon

A hammerspoon script that briefly highlights the active window when focused.
Lua
21
star
35

discord-transcriber

Use Google Cloud Speech to transcribe voice chats in Discord.
JavaScript
21
star
36

redux-waitfor

Reducer combinator that allows reducers to wait upon each other.
JavaScript
21
star
37

a-javascript-and-typescript-documentation-generator-based-on-typescript-compiler

🚧 📝 A documentation generator for JavaScript/TypeScript projects, based on TypeScript compiler, lol.
TypeScript
20
star
38

nes-apu-worklet

NES APU exposed as an HTML5 AudioWorklet. Generate 8-bit sounds fom Web Audio API! Powered by nes-js’s APU code.
HTML
19
star
39

gps

The simplest GPS tracking web-app!
19
star
40

super-silly-vortex

A silly recreation of the Rain Vortex at Jewel Changi Airport, but it’s node_modules instead of water. Made at Super Silly Hackathon 2019.
HTML
19
star
41

dtinth

19
star
42

pastebox

An Electron app for macOS that lets you paste image data from an application and drag it out as an image file to another application
HTML
18
star
43

shoutpraises

Web based remotely controlled worship lyrics presentation application.
JavaScript
18
star
44

vxchrome

A Chrome extension that listens to my voice, converts to text, and copies it to the clipboard.
CSS
18
star
45

1112.js

Automated pizza ordering using puppeteer.js
JavaScript
17
star
46

thaiWitter3

🐦 Super smooth web-based Twitter client I made in 2009 and maintained until 2013. Open sourced in 2018 for posterity.
JavaScript
17
star
47

xprs

A bundle of most-commonly-used middlewares for express, based on analyzing over 80,000 public GitHub repos on BigQuery.
TypeScript
16
star
48

pmd

My own simple Pomodoro timer, for Mac.
Ruby
16
star
49

.vimrc

My VIM settings.
Vim Script
15
star
50

obtain-github-app-installation-access-token

A simple CLI to obtain a GitHub App Installation Access Token
TypeScript
15
star
51

vxtron

An electron app that listens to my voice, converts to text, and copies it to the clipboard. Powered by Google Cloud Speech-To-Text API.
TypeScript
15
star
52

chordbook

A simple, interactive, block-based, color-coded, music-synchronized, transposale, optionally auto-scrolling chordbook web application.
HTML
15
star
53

react-performance-coach

How I optimize React apps to reduce wasted renders
TypeScript
15
star
54

bangkokipsum

Random Thai text generator
HTML
14
star
55

advent-of-code-2021

My Advent of Code 2021 solutions in Ruby (globally ranked 41st place)
14
star
56

friendlist

Advanced Friend List Manager for Facebook (new 2013 version)
JavaScript
13
star
57

GyroscratchAndroid

Kotlin
13
star
58

another-screen

Simple web-based app for local screen mirroring
HTML
13
star
59

img

A personal image hosting service, powered by Google Drive.
HTML
12
star
60

voiceout

Filter out vocal from audio, in real time. Demonstrating the use of HTML5 Web Audio API.
HTML
12
star
61

to.dt.in.th

Send @dtinth an encrypted message
HTML
12
star
62

ppqr.app

PromptPay QR code generator webapp… repo separated from dtinth/promptpay-qr.
TypeScript
12
star
63

countdown.html

Simple countdown timer — created during Live Coding (In the Dark) Session
HTML
12
star
64

vuetoy

Single-file Vue setup with no build tool. Ideal for building rapid prototypes or side-projects.
HTML
12
star
65

misheard

Stupid speech-to-text chat application
Vue
11
star
66

tuner-chrome

A chromatic tuner for your browser????
JavaScript
11
star
67

vscode-extension-to-suggest-commit-message-using-openai-codex

TypeScript
11
star
68

react-lambda

Anonymous functional components for React. How about using hooks inside hooks?
TypeScript
10
star
69

advent-of-code-2022

Ruby
Ruby
10
star
70

transaction-parser-th

Parse transaction information from SMS, notifications, etc...
TypeScript
10
star
71

screen-buffer

Screen buffer component used in ttycast (client and server).
JavaScript
10
star
72

jxapp

JavaScript
10
star
73

evalaas

Personal serverless prototyping platform on top of Cloud Run
JavaScript
10
star
74

2012-beyondthenetwork-visualization

Code that is used to generate the YouTube video that visualizes the tracker song Beyond the Network used in Bejeweled II
HTML
10
star
75

artstep

Fluent, painless, and beautiful Cucumber step definitions with promises, generators, and async functions support.
JavaScript
9
star
76

UCN-BMSE

A fork of UCN-Soft's BMSE, with long note support and helpers.
Visual Basic
9
star
77

json_pretty

Pretty-print your JSON!
PHP
9
star
78

dtinth.tools-android

Personal Android enhancement app. For personal use.
Kotlin
9
star
79

essay

📝 The real README driven development! Generate a JavaScript library out of an essay. Literate programming for the ES2015 era.
Shell
9
star
80

new-tab-page

My personal new tab page
JavaScript
9
star
81

StupidHackTH2-screen

Information screen used in The Stupid Hackathon Thailand #2
Vue
9
star
82

a-gif-frame-sequence-optimizer-optimized-for-screen-recordings

A GIF frame sequence optimizer optimized for screen recordings
JavaScript
9
star
83

atom-arpeggio

Define chords (simultaneously pressed keys) for speedy typing!
CoffeeScript
8
star
84

ysetter-hackathon-commit-board

JavaScript
8
star
85

live-comments-viewer

Making it easier to view comments on Facebook live
Vue
8
star
86

vscode-openai-codex-insert

Uses OpenAI Insert API to insert code suggestion at the current cursor position. Sometimes provides better suggestions than GitHub Copilot in a few cases.
TypeScript
8
star
87

bms.js

Be-Music Script reading and writing library for JavaScript
JavaScript
8
star
88

redux-send

An alternative way to write Redux apps. (Experimental.)
JavaScript
7
star
89

KeynoteFontChanger

Change the font of all text in all master slides in Keynote.
CoffeeScript
7
star
90

dtinthstagram

Simple, super-smooth, web-based instagram viewer. Compatible with Google Chrome and Fluid.
JavaScript
7
star
91

IO-MIDI-INSTRUMENT

Musical instruments for hackers.
JavaScript
7
star
92

encrypted

Dead simple library for encrypted secrets with shared key powered by TweetNaCl.js
JavaScript
7
star
93

openapi-trpc

Generate OpenAPI v3 document from a tRPC router, adhering to tRPC’s HTTP RPC Specification
TypeScript
7
star
94

screen-master

A presentation tool for hackers. Create live presentation with live data (e.g. scoreboard, names, etc.) using React and cast it to a projector screen.
TypeScript
7
star
95

tabe25m

ATOM PLUGIN TO FORCE YOU TO “TAKE A BREAK EVERY 25 MINUTES”
JavaScript
7
star
96

midi-rtc

A simple web application to transmit MIDI data over WebRTC
JavaScript
7
star
97

circumstance

Given-When-Then for your state-updating functions (e.g. Redux reducers).
6
star
98

markdown-report-action

Attachs some Markdown report to the GitHub Actions build
6
star
99

jamurust

Rust
6
star
100

cypress-docker-novnc

Run Cypress inside a Docker container with noVNC to access Cypress Test Runner in the web browser
6
star