Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/lionralfs/assert.macro

A babel macro to add assertions for development/testing purposes
https://github.com/lionralfs/assert.macro

assert assertions babel-macro babel-plugin-macros javascript macro

Last synced: 3 days ago
JSON representation

A babel macro to add assertions for development/testing purposes

Awesome Lists containing this project

README

        

# assert.macro [![Babel Macro](https://img.shields.io/badge/babel--macro-%F0%9F%8E%A3-f5da55.svg)](https://github.com/kentcdodds/babel-plugin-macros)

A babel macro to add assertions for development/testing purposes.

[![Build Status](https://travis-ci.com/lionralfs/assert.macro.svg?branch=master)](https://travis-ci.com/lionralfs/assert.macro)

## Installation

This project relies on [babel-plugin-macros](https://github.com/kentcdodds/babel-plugin-macros), you can install both from npm:

```sh
npm install --save-dev assert.macro babel-plugin-macros
```

#### Babel config

In your babel config, add `"macros"` to your plugins:

```json
{
"plugins": ["macros"]
}
```

#### Enabling the assertions

To include the assertions in the babel output, make sure you set the `ENABLE_ASSERTIONS` environment variable to `"true"`. For example:

```sh
ENABLE_ASSERTIONS=true npm run build
```

All usages of of the call to `assert`, including the import will be removed completely, if `ENABLE_ASSERTIONS` is **not** `"true"`.

## Usage

```js
import assert from 'assert.macro';

class ShoppingCart {
applyDiscount(discount) {
assert(discount > 0, "Discount can't be 0 or negative.");
assert(discount <= 1, "The discount shouldn't make it more expensive.");

this._total *= discount;
}
}
```

## Why

- Documents intent
- More explicit than comments
- Able to catch bugs

## Inspirations

- [Refactoring](https://martinfowler.com/books/refactoring.html) by Martin Fowler
- [Programming With Assertions](https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html) (Java)
- [Invariant](https://github.com/zertosh/invariant) by Facebook

## License

[MIT](LICENSE) © Lion Ralfs