Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected.

import util from 'util'

describe('Module', () => {
  it('should display all levels WITHOUT util', () => {
    const large = {
      level1: {
        level2: {
          message: 'At level 2!',
          level3: {
            message: 'At level 3!',
            level4: {
              message: 'At level 4!',
              level5: {
                message: 'At level 5!',
              },
            },
          },
        },
      },
    }
    console.dir(large, { depth: 5 })
  })

  it('should display all levels with util', () => {
    const large = {
      level1: {
        level2: {
          message: 'At level 2!',
          level3: {
            message: 'At level 3!',
            level4: {
              message: 'At level 4!',
              level5: {
                message: 'At level 5!',
              },
            },
          },
        },
      },
    }
    console.dir(util.inspect(large, { depth: 5 }))
  })
})

This is the output I receive:

    { level1: { level2: { message: 'At level 2!', level3: [Object] } } } { depth: 5 }

    { level1:
       { level2:
          { message: 'At level 2!',
            level3:
             { message: 'At level 3!',
               level4:
                { message: 'At level 4!', level5: { message: 'At level 5!' } } } } } }

I thought that console.dir should automatically handle this for me, but in the first test, after a depth of 2, I encounter [Object].

I even conducted a simple test outside of Jest and the console.dir function seemed to work fine. Can someone explain why this discrepancy occurs? Could Jest be overriding the default behavior of dir with its own depth settings?

const large = {
  level1: {
    level2: {
      message: 'At level 2!',
      level3: {
        message: 'At level 3!',
        level4: {
          message: 'At level 4!',
          level5: {
            message: 'At level 5!',
          },
        },
      },
    },
  },
}
console.dir(large, { depth: 5 })

The result is...

{ level1:
   { level2:
      { message: 'At level 2!',
        level3:
         { message: 'At level 3!',
           level4:
            { message: 'At level 4!', level5: { message: 'At level 5!' } } } } } }

Answer №1

In summary: The current Jest implementation ignores the second argument of console.dir(value, options).


Jest overrides the global console with its own version. In both the BufferedConsole and CustomConsole, you can see that the dir method is implemented as follows:

dir(firstArg: unknown, ...args: Array<unknown>): void {
  this._log('dir', format(firstArg, ...args));
}

The exact definition of the format function is not readily available, but based on Github examples, it likely behaves like this:

https://i.sstatic.net/RTNDt.png

export const format = (value: unknown): string =>
  typeof value === 'function'
    ? value.toString()
    : prettyFormat(value, {min: true});

The prettyFormat function offers a maxDepth option that appears to not be utilized in all 3 implementations.

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

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...

Is there a way to prevent Accordion propagation once it has been clicked for the first time?

I am facing a challenge with my accordion setup in Material-UI. I have an Accordion that contains a TextField inside the AccordionSummary. When the TextField is clicked, it opens the AccordionDetails where the rest of the form is displayed. However, I&apos ...

Distinguishing between TypeScript versions 2.0.x and 2.1.x using type definitions and filtering with a switch/case statement

@ngrx/store (an observable redux implementation for angular (2) ) utilizes a specific pattern to assign the correct type to a reducer. Check out the actual code here. export const ActionTypes = { FOO: type('foo'), BAR: type('bar&apos ...

Setting up a div as a canvas in Three.js: Step-by-step guide

Is there a way to adjust the JavaScript in this three.js canvas example so that the scene can be contained within a specific div element on a webpage? Here is the example: https://codepen.io/PedalsUp/pen/qBqvvzR I would like to use this as the background ...

Implementing the Google Maps API into a React application to generate a customized route between two specified points

I'm currently developing a React application that is designed to display the distance between two points on a map. Although I successfully implemented this feature using JavaScript and HTML, I am facing challenges in converting it to React as I am re ...

Making sure Angular picks up on $scope changes

Currently, I am in the process of developing my inaugural AngularJS application and am faced with the challenge of a directive not updating its view when there are changes to the array received from the service. Below is the structure of my directive: an ...

Utilize jQuery to showcase elements in a dropdown menu

Hey everyone, I'm working on an ASP.NET MVC4 project and I'm using a jQuery script on the edit page. However, I am encountering an issue with displaying elements on the page. Here is the initial HTML markup of my dropdown before any changes: & ...

Positioning a dropdown menu on top of a Google Map in React with JavaScript: Best Practices

I've been attempting to place a dropdown menu at a specific location on my Google Map, specifically in the top right (or top left is also acceptable). Below is the current output I am seeing: Here is the expected result: Modifications After trying ...

Updating image source dynamically with Flask

I am currently developing a face detection application using Flask. I aim to have the detected faces displayed in real-time on the HTML page. For the JavaScript aspect, I am utilizing getUserMedia to live stream camera images from the client to the server ...

What is the best way to assign unique IDs to automatically generated buttons in Angular?

Displayed below is a snippet of source code from an IONIC page dedicated to shapes and their information. Each shape on the page has two buttons associated with it: shape-properties-button and material-information-button. Is it possible to assign different ...

Discover the method for populating Select2 dropdown with AJAX-loaded results

I have a basic select2 box that displays a dropdown menu. Now, I am looking for the most effective method to refresh the dropdown menu every time the select menu is opened by using the results of an AJAX call. The ajax call will yield: <option value=1 ...

"Enhance your Vue 3 projects with a dynamic library featuring universal components and full

Currently, I am in the process of developing a Vue 3 component library using Vue 3, Vite, and TypeScript. The unique aspect about this library is that it installs as a plugin and registers all components as global entities. Here is an overview of how this ...

What is the best way to incorporate a PHP file into an HTML file?

Below is the code snippet from my index.php: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Voting Page</title> <script type="text/javascript" src="js/jquer ...

I'm running into an issue where my API calls are being duplicated

Every time I refresh the page, the network preview displays a duplicate API call to (ipaddress)/(portnumber)/admin/user-group?page=1&page_size=10&query= twice. I've tried making changes to the useEffect() and handleSearch() functions without s ...

Issue encountered with passport-local in TypeScript: Unable to utilize 'new' with an expression that does not have a call or construct signature

Currently, I am attempting to implement the passport-local package in TypeScript (version 2.0.0RC); however, a compiler error has arisen: Error TS2351: It is not possible to use 'new' with an expression lacking a call or construct signature. ...

What is the process for obtaining a new token in a Linnworks embedded application?

I decided to share my issue on this platform since the support from Linnworks is virtually non-existent. My dilemma involves a private embedded app created within Linnworks that showcases orders in spreadsheet format. The app, constructed using Vue.js and ...

What is the best approach to implementing React Hooks in Typescript when using Context?

I have implemented the following code snippet in my new React Native project to enable Dark Mode using TailwindCSS: import React, { createContext, useState, useContext } from 'react'; import { Appearance } from 'react-native'; import { ...

Developing dynamic checkbox components using jQuery - unusual behavior in Internet Explorer

I am dynamically creating checkbox elements using jQuery and appending them to a specified node as shown below var topics = ['All','Cat1','Cat2']; var topicContainer = $('ul#someElementId'); $.each( topics, functio ...

Encountering the error message "Unexpected token. Did you mean {'>'} or &gt;?" when trying to use an arrow function in React

I recently started learning React and Javascript. I encountered an error message that said: "Unexpected token. Did you mean {'>'} or &gt;?", specifically in relation to the "=>" part of the code below. This issue arose while I was worki ...

Express.js post request not functioning properly

I am currently in the process of developing a discussion-based Node.js/Express app and I am focusing on creating a discussion page. I have been attempting to test if my discussion controller file is properly linked, but for some reason every time I click t ...