Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

539
Vistas
Unit test asynchronous generator function in Jest

I would like to write a unit test for a generator function but I am not able to pass a properly mocked read stream (ReadStream) object.

Testable function:

  public async *readChunks(file: string, chunkSize: number): AsyncIterableIterator<Buffer> {
    if (!this.cwd) throw new Error('Working directory is not set!');

    const readStream: ReadStream = fs.createReadStream(path.join(this.cwd, file), {
      highWaterMark: chunkSize
    });

    for await (const chunk of readStream) yield chunk;
  }

Failed implementation (I tried different mocking of the createReadStream but without success):

describe('Work Dir Utils', () => {
  jest.mock('fs');

  let workDirUtils: WorkDirUtils;

  beforeEach(() => {
    (os.tmpdir as jest.Mock).mockReturnValue('/tmp');
    (fs.mkdtempSync as jest.Mock).mockReturnValue('/tmp/folder/pref-rand');
    (fs.createReadStream as jest.Mock).mockReturnValue({});
    workDirUtils = new WorkDirUtils();
    workDirUtils.createTempDir('pref-');
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should read chunks of a file using generator', async () => {
    for await (const chunk of workDirUtils.readChunks(
      path.join(__dirname, './fixtures/manifest.ts'),
      1024 * 1024 * 1024
    )) {
      expect(chunk).toBeInstanceOf(Buffer);
    }
  });
});

Any suggestions?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Actually, it turned out to be quite easy. In the end, I did not want to revoke the question. Maybe it will be useful for others.

jest.mock('fs');
jest.mock('tar');
jest.mock('os');
let workDirUtils: WorkDirUtils;

describe('Work Dir Utils', () => {
  beforeEach(() => {
    (os.tmpdir as jest.Mock).mockReturnValue('/tmp');
    (fs.mkdtempSync as jest.Mock).mockReturnValue('/tmp/folder/pref-rand');
    (fs.existsSync as jest.Mock).mockReturnValue(true);
    (fs.createReadStream as jest.Mock).mockReturnValue(Readable.from([path.join(__dirname, './fixtures/manifest.ts')]));
    workDirUtils = new WorkDirUtils();
    workDirUtils.createTempDir('pref-');
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should generator function throw an error', async () => {
    const workdirUtilsMock = new WorkDirUtils();

    const generator = workdirUtilsMock.readChunks('file-path', 5000);

    expect(generator.next).rejects.toThrow('Working directory is not set!');
  });

  it('should read chunks of a file using generator', async () => {
    const generator = workDirUtils.readChunks(path.join(__dirname, './fixtures/manifest.ts'), 1024 * 1024 * 1024);

    const response = await generator.next();

    expect(response).toBeInstanceOf(Object);
    expect(response.value).toEqual(path.join(__dirname, './fixtures/manifest.ts'));
  });
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda