All files / sportident/src testUtils.ts

100% Statements 55/55
100% Branches 10/10
100% Functions 15/15
100% Lines 39/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77    22x     22x 14x     22x 2x     124x 124x 124x     106x 106x 34x   72x 72x     218x   151x   22x 2558x 37x 37x 37x 2593x 2567x     37x                 22x     71x 71x 13x   71x 71x 10x 61x 33x   71x               22x 5x 5x 5x 5x 5x    
/* globals jest */
 
import _ from 'lodash';
import * as siProtocol from './siProtocol';
 
export const useFakeTimers = (): void => {
    jest.useFakeTimers();
};
 
export const runPromises = async (): Promise<void> => {
    await Promise.resolve();
};
 
export const advanceTimersByTime = async (msToRun: number): Promise<void> => {
    jest.advanceTimersByTime(msToRun);
    await Promise.resolve();
};
 
export const nTimesAsync = async (n: number, doThing: () => Promise<unknown>): Promise<void> => {
    if (n <= 0) {
        return;
    }
    await doThing();
    await nTimesAsync(n - 1, doThing);
};
 
export const getRandomInt = (numOptions: number): number => Math.floor(Math.random() * numOptions);
 
export const getRandomByte = (): number => getRandomInt(256);
 
export const getRandomByteExcept = (except: number[]): number => {
    except.sort((a, b) => Number(a) - Number(b));
    const numOptions = 256 - except.length;
    let randomValue = getRandomInt(numOptions);
    except.forEach((exceptedByte) => {
        if (randomValue >= exceptedByte) {
            randomValue += 1;
        }
    });
    return randomValue;
};
 
type GetRandomMessageOptions = {
    command?: number;
    parameters?: number[];
    numParameters?: number;
};
 
export const getRandomMessage = (
    options: GetRandomMessageOptions,
): siProtocol.SiMessageWithoutMode => {
    let command = getRandomByte();
    if (options.command !== undefined) {
        command = options.command;
    }
    let parameters: number[] = [];
    if (options.parameters !== undefined) {
        parameters = options.parameters;
    } else if (options.numParameters !== undefined) {
        parameters = _.range(options.numParameters).map(() => getRandomByte());
    }
    return {command: command, parameters: parameters};
};
 
export interface Mockable<T> {
    counts: {[key: string]: number};
    mocks: {[key: string]: (count: number) => T};
}
 
export const runMock = <T>(that: Mockable<T>, key: string, getDefaultResult: (count: number) => T): T => {
    const count = that.counts[key] || 0;
    const mockFunction = that.mocks[key] || getDefaultResult;
    const result = mockFunction(count);
    that.counts[key] = count + 1;
    return result;
};