jeudi 3 octobre 2019

Reset Jest mock of id generator on every test

I'm trying to mock id generation function. Content of my generateIdsSet.js file is:

import nanoid from 'nanoid/generate'

const generateId = (): string => {
  return nanoid('1234567890abcdefghijklmnopqrstuvwxyz', 5)
}

export const generateIdsSet = (setLength) => {
  const setIds = []

  for (let i = 0; i < setLength; i++) {
    setIds.push(generateId())
  }

  return setIds
}

In the mock file generateIdsSet.spec.js for generateIdsSet I need to create array of predictable ids. I came up with that implementation:

import { generateIdsSet } from './generateIdsSet.js'

jest.mock('nanoid/generate', () => {
  let value = 0

  return () => String(++value)
})

describe('generateIdsSet', () => {
  it('One element', () => {
    expect(generateIdsSet(1)).toEqual(['1'])
  })

  it('Four elements', () => {
    expect(generateIdsSet(4)).toEqual(['1', '2', '3', '4'])
  })

  ....
})

Everything is OK except that on every test counter doesn't reset to 1 and keeps incrementing for every call.

Maybe it's something obvious I'm missing but I can't figure it out. I will be grateful for the help.

Aucun commentaire:

Enregistrer un commentaire