Reputation: 619
I'm thinking how to mock transports. File (from winston node module). I'm using jest so __mocks__/winston.ts
is auto-loaded. I think that I can't mock it becouse there is new
// LoggerFactory.ts
import { transports, TransportInstance } from "winston";
...
const transportList: TransportInstance[] = [
new transports.File({
name: `${tag}-error`,
filename: `${dirname}${filename}.error.log`,
json: false,
level: "error",
zippedArchive: false,
maxFiles: 14,
maxsize: 100000000
}),
new transports.File({
name: `${tag}-info`,
filename: `${dirname}${filename}.log`,
json: false,
level: "info",
maxFiles: 10,
zippedArchive: false,
maxsize: 100000000
})
];
...
// __mocks__/winston.ts
const winston = {
????
};
export default winston;
error: TypeError: Cannot read property 'File' of undefined
Upvotes: 5
Views: 6289
Reputation: 127
In your test file, type the following at the top:
const mockWinstonLog = jest.fn()
jest.mock('winston', () => ({
createLogger: jest.fn(() => ({
log: mockWinstonLog,
})),
transports: {
Console: jest.fn(),
},
format: {
json: jest.fn(),
},
}))
You can then in your test cases check for:
expect(mockWinstonLog).toHaveBeenCalled()
Upvotes: 0
Reputation: 1682
For our winston test mocks in __mocks__/winston.js
, we do:
const logger = {
format: {
printf: jest.fn(),
timestamp: jest.fn(),
simple: jest.fn(),
colorize: jest.fn(),
combine: jest.fn()
},
transports: {
Console: jest.fn(),
File: jest.fn()
},
createLogger: jest.fn().mockImplementation(function(creationOpts) {
return {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn()
};
})
};
module.exports = logger;
We can then use the jest.fn()
call catchers to test for the logger. Generally we don't care about logging so this is just used not to generate log files during tests.
Upvotes: 3