Skip to content

Instantly share code, notes, and snippets.

@thomaskonrad
Created February 8, 2020 15:21
Show Gist options
  • Save thomaskonrad/bfd441f90bbaf2c2c9d03d4b0ff661ce to your computer and use it in GitHub Desktop.
Save thomaskonrad/bfd441f90bbaf2c2c9d03d4b0ff661ce to your computer and use it in GitHub Desktop.
Random Number Generator in TypeScript: Jest Unit Test
import { Crypto } from '@peculiar/webcrypto';
import RandomGenerator from '@/crypto/RandomGenerator';
Object.defineProperty(window, 'crypto', {
value: new Crypto(),
});
test('Random generator returns a 16 byte random sequence', () => {
const randomBytes1 = RandomGenerator.generateRandomBytes(16);
const randomBytes2 = RandomGenerator.generateRandomBytes(16);
expect(randomBytes1).toBeInstanceOf(Uint8Array);
expect(randomBytes1.length).toEqual(16);
expect(randomBytes2).toBeInstanceOf(Uint8Array);
expect(randomBytes2.length).toEqual(16);
expect(randomBytes1).not.toEqual(randomBytes2);
});
test('Random number generator returns a number between the given range', () => {
const min = 0;
const max = 7;
const randomNumber = RandomGenerator.generateRandomNumber(min, max);
expect(randomNumber).toBeGreaterThanOrEqual(min);
expect(randomNumber).toBeLessThanOrEqual(max);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment