Не могу воспроизвести. Это работает для меня.
logger.js
:
const winston = require('winston');
const logger = winston.createLogger({
level: 'debug',
format: winston.format.combine(winston.format.json(), winston.format.colorize(), winston.format.simple()),
transports:
process.env.NODE_ENV === 'production' ? [new winston.transports.Console()] : [new winston.transports.Console()],
});
module.exports = logger;
logger.test.js
:
jest.mock('winston');
const winston = require('winston');
let mockJson;
let mockColorize;
let mockSimple;
let mockCombine;
let mockConsole;
let mockTransports;
let mockFormat;
beforeEach(() => {
mockJson = jest.fn(() => 'mock json');
mockColorize = jest.fn(() => 'mock colorize');
mockSimple = jest.fn(() => 'mock simple');
mockCombine = jest.fn();
mockConsole = jest.fn();
mockTransports = {
Console: mockConsole,
};
mockFormat = {
json: mockJson,
colorize: mockColorize,
combine: mockCombine,
simple: mockSimple,
};
winston.format = mockFormat;
winston.transports = mockTransports;
winston.createLogger.mockImplementation(() => ({ info: jest.fn() }));
require('./logger');
});
test('default behavior', () => {
expect(mockTransports.Console).toHaveBeenCalledTimes(1);
expect(mockFormat.json).toHaveBeenCalledTimes(1);
expect(mockFormat.colorize).toHaveBeenCalledTimes(1);
expect(mockFormat.simple).toHaveBeenCalledTimes(1);
expect(mockFormat.combine).toHaveBeenCalledTimes(1);
expect(mockFormat.combine).toHaveBeenCalledWith('mock json', 'mock colorize', 'mock simple');
});
test('default behavior with production env', () => {
process.env.NODE_ENV = 'production';
expect(winston.createLogger).toHaveBeenCalledTimes(1);
});
test('default behavior with development env', () => {
process.env.NODE_ENV = 'development';
expect(winston.createLogger).toHaveBeenCalledTimes(1);
});
Результаты модульного теста с отчетом о покрытии:
PASS stackoverflow/60566915/logger.test.js (9.303s)
✓ default behavior (776ms)
✓ default behavior with production env
✓ default behavior with development env (1ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 50 | 100 | 100 |
logger.js | 100 | 50 | 100 | 100 | 7
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 10.625s
исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60566915