Home > Net >  Use Jest to test appendfilesync
Use Jest to test appendfilesync

Time:08-29

I am trying to write a test for appendfilesync. I call this when using a logger and so I have 1 line of code not covered. Here is the code (note: using tslog for logger)

export function logToTransport(logObject: ILogObject) {
  appendFileSync('monopoly_deal.log', JSON.stringify(logObject)   '\n');
}

I've tried mocking up 'fs' which can work so that nothing actually writes to file but I don't actually test the writing. Here is start of my test code to set things up:

const log: Logger = new Logger({ name: 'card_types_test' });
    log.attachTransport(
      {
        silly: CardTypes.logToTransport,
        debug: CardTypes.logToTransport,
        trace: CardTypes.logToTransport,
        info: CardTypes.logToTransport,
        warn: CardTypes.logToTransport,
        error: CardTypes.logToTransport,
        fatal: CardTypes.logToTransport,
      },
      'info',
    );

// Here I would need to setup a jest.spyon I think to intercept the call but not sure how to do it. Something like const spy = jest.fn(CardTypes.logToTransport);

log.info('test'); // Logs to file
expect(spy).toequal({object with my data}); // I didn't put what object would actually look like for brevity.

Any guidance on how to mock up writing to files is greatly appreciated along with any other critiques (still a junior level programmer at best).

CodePudding user response:

You should test the code logic of logToTransport function rather than fs.appendFileSync method. fs.appendFileSync is a built-in method of Node.js and it's well tested.

You can only mock the fs.appendFileSync method, this way is called mocking partials. We are going to test the implementation detail of logToTransport function, this test strategy is called white-box testing.

Besides, we can use jest.isMockFunction to verify if we do the mocking partials successfully.

E.g.

index.ts:

import { appendFileSync } from 'fs';

type ILogObject = any;
export function logToTransport(logObject: ILogObject) {
  appendFileSync('monopoly_deal.log', JSON.stringify(logObject)   '\n');
}

index.test.ts:

import fs from 'fs';
import { logToTransport } from '.';

jest.mock('fs', () => ({
  ...(jest.requireActual('fs') as typeof fs),
  appendFileSync: jest.fn(),
}));
describe('73466276', () => {
  test('should pass', () => {
    expect(jest.isMockFunction(fs.appendFileSync)).toBeTruthy();
    expect(jest.isMockFunction(fs.appendFile)).toBeFalsy();
    logToTransport({ level: 'debug', payload: { name: 'teresa teng' } });
    expect(fs.appendFileSync).toBeCalledWith(
      'monopoly_deal.log',
      JSON.stringify({ level: 'debug', payload: { name: 'teresa teng' } })   '\n'
    );
  });
});

Test result:

 PASS  stackoverflow/73466276/index.test.ts (11.306 s)
  73466276
    ✓ should pass (3 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.012 s
  • Related