Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda