Simulating a winston logger in jest testing

I am pondering how to create mock transports for the File module within the Winston node package. While utilizing Jest, the __mocks__/winston.ts file is automatically loaded. My dilemma lies in the fact that I am unable to mock it due to the presence of the new keyword.

// 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;

An error has surfaced: TypeError: Cannot read property 'File' of undefined

Answer №1

When creating mocks for our winston testing in the file __mocks__/winston.js, we follow this structure:

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;

By using the jest.fn() catchers, we are able to test the logger functionality without creating log files during the testing process, as logging is typically not the main focus of our tests.

Answer №2

Make sure to include the following code at the beginning of your test file:

const mockWinstonLog = jest.fn()
jest.mock('winston', () => ({
  createLogger: jest.fn(() => ({
    log: mockWinstonLog,
  })),
  transports: {
    Console: jest.fn(),
  },
  format: {
    json: jest.fn(),
  },
}))

For your test scenarios, verify the following:

expect(mockWinstonLog).toHaveBeenCalled()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to duplicate a Select input and attach it to a div using Jquery

Recently, I was working on a Select input with the name "item" as an example. <select name="item"> <option value="1">1</option> <option value="2" selected="selected">2</option> <option value="3">3</option> <opt ...

Utilize the NPM package manager in the zsh shell on Ubuntu within a Windows 10

After transitioning to the zsh for coding in Python and configuring the environment variables, I am now encountering an issue while trying to start a small JavaScript project. The problem arises when attempting to use npm, as initializing the repo results ...

My Angular2+ application is encountering errors with all components and modules displaying the message "Provider for Router not found."

After adding routing to my basic app through app.routing.ts, I encountered errors in all of my test files stating that no Router is provided. To resolve the errors, I found that I can add imports: [RouterTestingModule], but is there a way to globally impo ...

Encountering a POST 504 error while attempting to proxy an Angular application to a Node server

error message: Failed to connect to http://localhost:4200/api/user/login with a 504 Gateway Timeout error. Encountered this issue while attempting to set up a login feature in my Angular application and establish communication with the Express backend. Th ...

Is it possible for me to determine whether a javascript file has been executed?

I am currently working with an express framework on Node.js and I have a requirement to dynamically change the value (increase or decrease) of a variable in my testing module every time the module is executed. Is there a way to determine if the file has ...

Troubles encountered when trying to execute mocha within Firebase functions

My latest project involved developing a Node/Typescript app that interacted with data from Firebase Cloud Firestore. The app performed flawlessly, and I conducted endpoint testing using simple mocha commands on the generated .js file. Below is an example o ...

What is the best way to implement vuelidate when dealing with an array of objects?

In my form questionnaire, I am looping through an array of objects. Each object has five properties, but only one property needs validation. The validation setup in the component looks like this: specificGifts: { $each: { passThrough: { ...

Guide on displaying multiple views along with their respective models fetched through AJAX in Backbone

Hey there! I'm currently working on painting a screen with multiple models and associated views in backbone. To achieve this, I have separate ajax calls to fetch data for these views. Initially, I thought using the jQuery function $when(ajaxcall1, aja ...

What could be the reason for the function providing the value of just the initial input?

Why am I only getting "White" when I click on the colors? I can't seem to get any other values to appear on the screen. I'm confused about what mistake I might be making here. var x = document.getElementById("mySelect").value; function myFunc ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Creating a personalized design for MUI TextField spin button

Looking to customize the appearance of the up/down spin buttons in MUI TextField. https://i.sstatic.net/DcG66.png Desiring white arrows and a black surrounding area that's slightly larger, akin to this: https://i.sstatic.net/ZxMJw.png I'm aware ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

What is the best way to update image CSS following a rotation using JavaScript?

Discover a neat CSS trick for always centering an image in a div, regardless of its size or aspect ratio. <style> .img_wrap { padding-bottom: 56.25%; width: 100%; position: relative; overflow: hidden; } #imgpreview { display: bl ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

Nested Tab Generation on the Fly

My goal is to create dynamically nested tabs based on my data set. While I have successfully achieved the parent tabs, I am encountering an issue with the child tabs. Code $(document).ready(function() { var data1 = [["FINANCE"],["SALE"],["SALE3"]]; var da ...

Utilize a MongoDB query to locate a single document and include a conditional statement within the update operation

I've been struggling with this problem for quite some time now and I could really use some guidance from experts here on SO. Essentially, what I am trying to achieve is to locate a specific document using a provided _id, and then execute a conditional ...

The callback response in Node's exec function is behaving incorrectly

When I have a route handling a URL post request, I am running an exec on a bash command. Strangely, the console.log is working fine indicating that the bash command ends and the callback is triggered. However, for some reason, the response fails to send ...

What is the best way to access the current value and name of a textbox in real-time using

How can I retrieve the value of a textbox in JavaScript using onblur and on keyup events, while also performing real-time checking for each individual textbox using "this keyword"? Here is my JSFiddle link. Can you assist me in modifying it? ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

Transformation of Python code into Blockly blocks

As the founder of edublocks.org, I am interested in adding Python to Blocks functionality on the platform. At the moment, users can only transition from Blocks to Python. Is there anyone who has experience with this and can provide guidance on how to achi ...