简体   繁体   中英

How to mock Logger in jest

How shall I jest mock the Logger method / instance? I did try online resources but could not find anything that works. Can someone please help me? Just mocking of logger method would be enough. I was able to mock other code. I can't test error condition because of that.

import rp from "request-promise-native";
import BookLogger from "Book-logger";
const logger = BookLogger.getLogger('Book-service', BookLogger.LOG_LEVEL.INFO);

export class BookService {

@param bookCategory id of book category
@param boooks list of books

public static async getAllBookInCategory(bookCategory: string) {

        try {
            const neededInfo = {
                url: `https://${process.env.BOOK_HOST}/bookapi/${process.env.BOOKAPI_VERSION}/iterative/bookCategory/${ bookCategory }/books/all `,
                method: 'GET',
            }

            const result = await BookService.makeRequest(bookCategory, neededInfo);

            return await rp(result);
        } catch(error) {
            logger.error(`Failed to get All Books in given category ${error}`)
        }
}

Here is the solution:

main.ts :

import BookLogger from './Book-logger';
const logger = BookLogger.getLogger('Book-service', BookLogger.LOG_LEVEL.INFO);

export function main() {
  const error = new Error('Internal server error');
  logger.error(`Failed to get All Books in given category ${error}`);
}

Book-logger.ts :

export default class BookLogger {
  public static LOG_LEVEL = {
    INFO: 'INFO',
  };
  public static getLogger(name, level) {
    return {
      error: (message) => {
        console.error(message);
      },
    };
  }
}

main.test.ts :

import { main } from './main';
import BookLogger from './Book-logger';

jest.mock('./Book-logger.ts', () => {
  const mLogger = {
    error: jest.fn(),
  };
  return {
    LOG_LEVEL: require.requireActual('./Book-logger.ts').default.LOG_LEVEL,
    getLogger: jest.fn(() => mLogger),
  };
});

describe('main', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });
  it('should mock logger correctly', () => {
    const logger = BookLogger.getLogger('Book-service', BookLogger.LOG_LEVEL.INFO);
    main();
    expect(jest.isMockFunction(logger.error)).toBeTruthy();
    const error = new Error('Internal server error');
    expect(logger.error).toBeCalledWith(`Failed to get All Books in given category ${error}`);
  });
});

Unit test result with coverage report:

 PASS  src/stackoverflow/59366107/main.test.ts
  main
    ✓ should mock logger correctly (4ms)

----------------|----------|----------|----------|----------|-------------------|
File            |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files       |    83.33 |      100 |       50 |    81.82 |                   |
 Book-logger.ts |    71.43 |      100 |    33.33 |    66.67 |               6,8 |
 main.ts        |      100 |      100 |      100 |      100 |                   |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.562s, estimated 11s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59366107

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM