Skip to content

Commit

Permalink
Add test that checks if regeneration of random values is triggered (#285
Browse files Browse the repository at this point in the history
)

Using crypto.randomFill in test cause that result of algorithm execution become unpredictable
Mock crypto.randomFill implementation for checking algorithm correctness
  • Loading branch information
TheSeally authored Jun 13, 2021
1 parent c28766d commit 307a1e0
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions test/async.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,13 @@ for (let type of ['node', 'browser']) {
describe(`${type}`, () => {
let { nanoid, customAlphabet, random } = type === 'node' ? node : browser

function mock(callback) {
crypto.randomFill = callback
jest.resetModules()
nanoid = require('../async').nanoid
}

describe('nanoid', () => {
function mock(callback) {
crypto.randomFill = callback
jest.resetModules()
nanoid = require('../async').nanoid
}
if (type === 'node') {
let originFill = crypto.randomFill
afterEach(() => {
Expand Down Expand Up @@ -127,6 +128,13 @@ for (let type of ['node', 'browser']) {
})

describe('customAlphabet', () => {
if (type === 'node') {
let originFill = crypto.randomFill
afterEach(() => {
mock(originFill)
})
}

it('has options', async () => {
let nanoidA = customAlphabet('a', 5)
let id = await nanoidA()
Expand Down Expand Up @@ -160,6 +168,21 @@ for (let type of ['node', 'browser']) {
}
expect(max - min).toBeLessThanOrEqual(0.05)
})

if (type === 'node') {
it('should call random two times', async () => {
let randomFillMock = jest.fn((buffer, callback) =>
callback(null, [220, 215, 129, 35, 242, 202, 137, 180])
)
mock(randomFillMock)

let nanoidA = customAlphabet('a', 5)
let id = await nanoidA()

expect(randomFillMock).toHaveBeenCalledTimes(2)
expect(id).toEqual('aaaaa')
})
}
})
})
}

0 comments on commit 307a1e0

Please sign in to comment.