Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add random spinner #47

Merged
merged 8 commits into from
Jul 18, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
declare namespace cliSpinners {
type SpinnerName =
| 'random'
| 'dots'
| 'dots2'
| 'dots3'
Expand Down
10 changes: 10 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

const spinners = Object.assign({}, require('./spinners.json'));

const spinnersList = Object.keys(spinners);

Object.defineProperty(spinners, 'random', {
get() {
const randomIndex = Math.floor(Math.random() * spinnersList.length);
const spinnerName = spinnersList[randomIndex];
return spinners[spinnerName];
}
});

module.exports = spinners;
// TODO: Remove this for the next major release
module.exports.default = spinners;
33 changes: 33 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,41 @@
import test from 'ava';
import cliSpinners from '.';

function mockMathRandom(fixedResult) {
unMockMathRandom();
const originalImpl = Math.random;
Math.random = () => fixedResult;
Math.random.originalImpl = originalImpl;
}

function unMockMathRandom() {
if (Math.random.originalImpl) {
Math.random = Math.random.originalImpl;
}
}

test('main', t => {
t.is(typeof cliSpinners, 'object');
t.is(cliSpinners.dots.interval, 80);
t.true(Array.isArray(cliSpinners.dots.frames));
});

test('random getter', t => {
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
const spinnersList = Object.keys(cliSpinners)
// TODO: remove this filter when "module.exports.default = spinners" is removed from index.js;
.filter(key => key !== 'default')
.map(key => cliSpinners[key]);

// Should always return an item from the spinners list
t.true(spinnersList.includes(cliSpinners.random));

// Should return the first spinner when math.random is the min value
mockMathRandom(0);
t.is(cliSpinners.random, spinnersList[0]);

mockMathRandom(0.99);
// Should return the last spinner when math.random is the max value
t.is(cliSpinners.random, spinnersList[spinnersList.length - 1]);

unMockMathRandom();
});