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 using the kleur API. The API exposed is 100% the same as kleur.
Table of contents
Why use this module?
Have you ever wonder, how to test the output of function calls like the following?
import { bgRed, white } from 'kleur'
assert.equal(bgRed().white('Error'), 'Error')
Well, you can make use of modules like strip-ansi to strip the ansi codes and get back the plain string.
import { bgRed, white } from 'kleur'
import stripAnsi from 'strip-ansi'
assert.equal(stripAnsi(bgRed().white('Error')), 'Error')
However, this module takes a step forward with a fake colors API, that you can use during testing to reliably test the output.
import { FakeColors } from '@poppinss/colors'
const colors = new FakeColors()
assert.equal(colors.bgRed().white('Error'), 'bgRed(white(Error))')
Usage
Install the package from npm registry as follows:
npm i @poppinss/colors
yarn add @poppinss/colors
and then use it as follows:
import { Colors } from '@poppinss/colors'
const colors = new Colors()
When wring tests, you can make your code rely on FakeColors
object instead of the Colors
object. For example:
import { FakeColors } from '@poppinss/colors'
const colors = new FakeColors()
Raw Implementation
The Raw
implementation exposes the same API as kleur, but does not apply any formatting/colors to the output string. You can use the raw implementation when the terminal does not support colors. For example:
import { Colors, Raw } from '@poppinss/colors'
import { level } from 'color-support'
const colors = level > 0 ? new Colors() : new Raw()
colors.red('hello world')
Finally, there is a method called getBest
to get the best available implementation instance for your runtime.
import { getBest } from '@poppinss/colors'
const colors = getBest(false)
The getBest
method returns following outputs
- An instance of Raw when the terminal does not supports colors.
- An instance of FakeColors when the first argument passed to the method is
true
. - Otherwise returns an instance of Colors.