1 import shuffle from './shuffle';
3 describe('shuffle()', () => {
4 it('returns empty array when empty array is passed', () => {
5 const result = shuffle([]);
7 expect(result).toStrictEqual([]);
10 it('returns same array when array of length 1 is passed', () => {
13 const result = shuffle(input);
15 expect(result).toStrictEqual(input);
18 it('return array of same length', () => {
19 const input = [0, 1, 2, 3, 4, 5, 6];
21 const result = shuffle(input);
23 expect(result.length).toBe(input.length);
26 it('does not mutate items in the array', () => {
27 const input = [0, 1, 2, 3, 4, 5, 6];
29 const result = shuffle(input);
31 expect(result.sort()).toStrictEqual(input.sort());
34 it('shuffles as expected when random values are mocked', () => {
35 jest.spyOn(Math, 'random')
36 .mockReturnValueOnce(0.8824154514152932)
37 .mockReturnValueOnce(0.22451795440520217)
38 .mockReturnValueOnce(0.5352346169904075)
39 .mockReturnValueOnce(0.9121122157867988)
40 .mockReturnValueOnce(0.008603728182251968)
41 .mockReturnValueOnce(0.26845647050651644)
42 .mockReturnValueOnce(0.44258055272215036)
43 .mockReturnValueOnce(0.08296662925946618)
44 .mockReturnValueOnce(0.4341574602173227);
45 const input = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
47 const result = shuffle(input);
49 expect(result).toStrictEqual([3, 9, 5, 7, 1, 0, 6, 4, 2, 8]);
52 describe('when array is of length 2', () => {
53 it('swaps items when random value is < 0.5', () => {
54 jest.spyOn(Math, 'random').mockReturnValue(0.49);
57 const result = shuffle(input);
59 expect(result).toStrictEqual([1, 0]);
62 it('does not swap items when random value is = 0.5', () => {
63 jest.spyOn(Math, 'random').mockReturnValue(0.5);
66 const result = shuffle(input);
68 expect(result).toStrictEqual(input);
71 it('does not swap items when random value is > 0.5', () => {
72 jest.spyOn(Math, 'random').mockReturnValue(0.51);
75 const result = shuffle(input);
77 expect(result).toStrictEqual(input);