Running a Single Test Only Using Jest

Jest provides a convenient way to run only one unit test at a time.

First, run only the single test file which contains the single test to run, similar to the following:

jest my-test-suite.spec.js

The single test in the suite that we wish to run should be changed to use it.only() as in the example below:

describe('My test suite', () => {
  it('should meet condition 1', () => {
    expect(condition1).toEqual(true)
  })

  it.only('should meet condition 2', () => {
    expect(condition2).toEqual(true)
  })

  it('should meet condition 3', () => {
    expect(condition3).toEqual(true)
  })
})

Jest will run only the second test, and will show the others as skipped.

Note that it.only() can be used multiple times in the file, so that we can run only two or only several jest tests as desired.

Another way to run several tests only is to select the tests that should not be run, and use it.skip() for these. The specific tests only will be skipped.

There is also a way to run a single test suite at a time inside a file, which is handy for running a group of related tests: describe.only().

Convenient Ways to Print Out Entire Objects in JavaScript

Quick debugging in JavaScript often requires one to print out or log a full object to see what values it contains.

The usual console log can often print “[Object object]”, which is not useful.

Some convenient ways to see the entire object in logs are below.

Using the %o format specifier, which means “formatted as an object”:

console.log("%o", myObject)

Using the dir function:

console.dir(myObject)

The “dir” in console.dir() comes from “directory”, as in a directory of all the properties of the object. This always outputs a full hierarchical representation of the object.

Another way is to fully serialize the object into a JSON string:

console.log(JSON.stringify(myObject))

This is very useful especially in the context of loggers, so if logger is an instance of a logging object (such as a Winston logger), then we can log a complete JSON object using:

logger.info(JSON.stringify(myObject))