Home > front end >  How to unit test a javascript object with value?
How to unit test a javascript object with value?

Time:09-24

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');

CodePudding user response:

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
  • Related