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

371
Vistas
Why java script fs.readFileSync is not getting mocked?

i have a fs.readFileSync function that i need to mock using jest. i have tried the below code.

my original file which i want to test.

   const fs = require('fs');


const read_file = (path) => {
  try {
    const data = fs.readFileSync(path, 'utf8');
    return data;
  } catch (err) {
    console.error('Error in read_file', err);
    throw err;
  }
};

const getSecret = secretName => {
  try {
    return read_file(`/etc/secrets/${secretName}.txt`);
  } catch (err){
    throw err;
  }
};

const secretConfig = {
  kafka_keystore_password: getSecret('kafka_keystore_password')
};

module.exports = secretConfig;

here is my test case

const secret = require('./secret');
let fs = require('fs')
jest.mock('fs');






describe('secret read files', () => {
    afterEach(jest.restoreAllMocks);
  it('should read secret from file', () => {
    //fs.readFileSync.mockReturnValue("randomPrivateKey");  
    fs.readFileSync.mockResolvedValue("randomPrivateKey")
    const secretMessage = secret.kafka_keystore_password;
    //expect(fs.readFileSync).toHaveBeenCalled();
    expect(secretMessage).toEqual('randomPrivateKey');

  })

})

describe('getSecretsFromFile', () => {
    const secret = 'secret';
    const secrets = { mySecret: secret };
  
    afterEach(jest.restoreAllMocks);
  
    it('returns secrets if file is present', () => {
      fs.existsSync.mockReturnValue(true);
      fs.readFileSync.mockReturnValue('randomPrivateKey');
  
      const secretMessage = secret.kafka_keystore_password;
      expect(secretMessage).toEqual('randomPrivateKey');
    });
});
    

and i get the following error.

FAIL src/config/secret.test.js ● secret read files › should read secret from file

expect(received).toEqual(expected) // deep equality

Expected: "randomPrivateKey"
Received: undefined

  15 |     const secretMessage = secret.kafka_keystore_password;
  16 |     //expect(fs.readFileSync).toHaveBeenCalled();
> 17 |     expect(secretMessage).toEqual('randomPrivateKey');
     |                           ^
  18 |
  19 |   })
  20 |

  at Object.<anonymous> (src/config/secret.test.js:17:27)

● getSecretsFromFile › returns secrets if file is present

expect(received).toEqual(expected) // deep equality

Expected: "randomPrivateKey"
Received: undefined

  32 |   
  33 |       const secretMessage = secret.kafka_keystore_password;
> 34 |       expect(secretMessage).toEqual('randomPrivateKey');
     |                             ^
  35 |     });
  36 | });
  37 |     

  at Object.<anonymous> (src/config/secret.test.js:34:29)

help me fix this .

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

0

try:

const fs = {
readFileSync: jest.fn(() => ({ message: 'Test'}))
}

to mock the fs readFileSync message.

But I don't see how this test is ever going to pass because you're returning value "Test"

but checking for randomPrivateKey

expect(secretMessage).toEqual('randomPrivateKey');

Without seeing what's going on inside the code it's difficult to say but I am assuming you might want to change that line to:

expect(secretMessage).toEqual('test');

As test is the value your mocking alternatively return randomPrivateKey from the mock.

I'm having to make a load of assumptions here because I don't know-how secret.kafka_keystore_password is calculated. I'm assuming it just returns the whatever the fs.readFileSync returns.7

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