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

231
Vistas
How to unit test a javascript object with value?

I have a js file where i read some value and load the results into a variable . the benefit i get is i dont have to read from file everytime i need it . i can simply import the object and use it.

however i dont know how to write unit test for it.

    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;

i use jest to write test cases.

i have tried something like this , but still the object resolves to undefined.

const secretConfig = require('./secret');
const fs = require('fs');
jest.mock('fs');
fs.readFileSync.mockReturnValue('randomPrivateKey');


 

describe('secret read files', () => {
    
  it('should read secret from file', async () => {
    const secretMessage = secretConfig.kafka_keystore_password;
    expect(secretMessage).toEqual('randomPrivateKey');

  })

})

secret read files › should read secret from file

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

Expected: "randomPrivateKey"
Received: undefined

  18 |     const secretMessage = secretConfig.kafka_keystore_password;
  19 |     //expect(fs.readFileSync).toHaveBeenCalled();
> 20 |     expect(secretMessage).toEqual('randomPrivateKey');
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your test is correct. The problem is that you need to mock before require the ./secret module because the getSecret method will be executed immediately when the module is required. At this time, the fs.readFileSync has not been given a mocked value yet.

const fs = require('fs');
fs.readFileSync.mockReturnValue('randomPrivateKey');
const secretConfig = require('./secret');

jest.mock('fs');

describe('secret read files', () => {
  it('should read secret from file', async () => {
    const secretMessage = secretConfig.kafka_keystore_password;
    expect(secretMessage).toEqual('randomPrivateKey');
  });
});

test result:

> jest "-o" "--coverage"

 PASS  examples/69283738/secret.test.js (7.265 s)
  secret read files
    ✓ should read secret from file (2 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   76.92 |      100 |     100 |   76.92 |                   
 secret.js |   76.92 |      100 |     100 |   76.92 | 8-9,17            
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        7.794 s
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