Search code examples
typescriptunit-testingsinonwinstonsinon-chai

How write unit test for configure winston with sinon?


I wrote configure for winstin:

import {createLogger, format, Logger, transports} from "winston";

export const logger: Logger = createLogger({
    level: 'debug',
    format: format.combine(
        format.timestamp(),
        format.json()
    ),
    transports: [
        new transports.Console()
    ]
});

But I don't know how write unit test for this configure.


Solution

  • Here is the unit test solution using proxyquire:

    logger.ts:

    import { createLogger, format, Logger, transports } from 'winston';
    
    export const logger: Logger = createLogger({
      level: 'debug',
      format: format.combine(format.timestamp(), format.json()),
      transports: [new transports.Console()],
    });
    

    logger.test.ts:

    import proxyquire from 'proxyquire';
    import sinon from 'sinon';
    
    describe('61027051', () => {
      it('should pass', () => {
        const winstonStub = {
          createLogger: sinon.stub(),
          format: {
            combine: sinon.stub(),
            timestamp: sinon.stub(),
            json: sinon.stub(),
          },
          transports: {
            Console: sinon.stub(),
          },
        };
        proxyquire('./logger', {
          winston: winstonStub,
        });
        sinon.assert.calledWith(winstonStub.createLogger, {
          level: 'debug',
          format: sinon.match.any,
          transports: sinon.match.array,
        });
      });
    });
    

    unit test result with 100% coverage:

      61027051
        ✓ should pass (1999ms)
    
    
      1 passing (2s)
    
    -----------|---------|----------|---------|---------|-------------------
    File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    -----------|---------|----------|---------|---------|-------------------
    All files  |     100 |      100 |     100 |     100 |                   
     logger.ts |     100 |      100 |     100 |     100 |                   
    -----------|---------|----------|---------|---------|-------------------