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    23x     23x 14x     23x 2x     124x 124x 124x     106x 106x 34x   72x 72x     216x   147x   23x 2558x 39x 39x 39x 2595x 2566x     39x                 23x     71x 71x 13x   71x 71x 10x 61x 32x   71x               23x 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;
};