Colors
Wrapper on top of Kleur with support for testing color calls.
This module is a wrapper on top of Kleur to make it easier to test the output generated by the kleur API. The API exposed is 100% the same as kleur.
Table of contents
Why use this module?
This module attempts to solve two specific problems.
- Make it easier to test strings using kleur color transformations.
- Provide a alternate implementation for non-tty terminals.
The problem
Let's imagine you are writing a test to ensure that function dummy
outputs an error message to the console in certain situation.
import { bgRed } from 'kleur'
function dummy () {
if (someCondition) {
console.log(bgRed().white('Error'))
}
}
You may attempt to test the output as follows:
const output = trapConsoleMessage()
dummy()
assert.equal(output, 'Error')
The assertion will fail, since the string Error
has ansi sequences applied to it to make it colorful.
To workaround this behavior, you can use a module like strip-ansi to string the ansi sequences and write assertions against the plain string.
import stripAnsi from 'strip-ansi'
const output = trapConsoleMessage()
dummy()
assert.equal(stripAnsi(output), 'Error')
Now, your assertions are passing, but there is no way to know which kleur transformations were applied to the string.
Our solution
Instead of relying on strip-ansi
, we ship with an alternative implementation of kleur, which doesn't apply ansi sequences at first place. Example:
import { FakeColors } from '@poppinss/colors'
const colors = new FakeColors()
const output = colors.bgRed().white('Error')
assert.equal(output, 'bgRed(white(Error))')
Notice the difference in the output? Instead of applying the background color and the text color. We wrap the value inside the applied transformations and return it back as a string.
How to use it in real world?
At AdonisJS, we rely on the NODE_ENV
environment variable to decide the implementation to choose. For example:
import { FakeColors, Colors } from '@poppinss/colors'
export default const colors = process.env.NODE_ENV === 'testing'
? new FakeColors()
: new Colors()
Now, inside the entire codebase, we import the above helper for colorizing output.
import colors from './helpers/colors'
colors.red('Error')
Installation
Install the package from npm registry as follows:
npm i @poppinss/colors
yarn add @poppinss/colors
and then use it as follows:
import {
FakeColors,
Colors,
Raw,
} from '@poppinss/colors'
const colors = new Colors()
const fakeColors = new FakeColors()
const rawColors = new Raw()