Home Web Front-end JS Tutorial How to temporarily silence logs in tests

How to temporarily silence logs in tests

Nov 30, 2024 am 10:54 AM

Logger package in Changesets source code provides a documentation about silencing log message in tests. This got me wonder how Changesets do it and made me look into its source code.

Changesets repository search for silencing logs

I searched for temporarilySilenceLogs across the Changesets repo using Github search.

How to temporarily silence logs in tests

What made me choose to search for temporarilySilenceLogs is the fact that it is mentioned in the Logger

package Readme.

1

2

3

4

5

6

7

import { temporarilySilenceLogs } from "@changesets/test-utils";

import { log } from "@changesets/logger";

temporarilySilenceLogs();

// Now the logs in this test file are not actually logged to std out

log("I am not logged");

// Use console.log to log messages in tests if required

console.log("Yay, I am logged");

Copy after login

When you are trying to understand the source code, you can use documentation as your starting point and search for variables and functions to set the direction for your exploration when you are dealing with large projects like Changesets.

temporarilySilenceLogs

The below code is picked from Changesets source code.

How to temporarily silence logs in tests

This function accepts a function as argument and then silences the logs using a function named createLogSilencer.

Pay attention to the setup function here:

1

2

3

4

5

6

const dispose = silencer.setup();

try {

 await testFn();

} finally {

 dispose();

}

Copy after login

createLogSilencer

Below code is picked from Changesets

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

const createLogSilencer = () => {

  const originalLoggerError = logger.error;

  const originalLoggerInfo = logger.info;

  const originalLoggerLog = logger.log;

  const originalLoggerWarn = logger.warn;

  const originalLoggerSuccess = logger.success;

 

  const originalConsoleError = console.error;

  const originalConsoleInfo = console.info;

  const originalConsoleLog = console.log;

  const originalConsoleWarn = console.warn;

 

  const originalStdoutWrite = process.stdout.write;

  const originalStderrWrite = process.stderr.write;

 

  return {

    setup() {

      logger.error = jest.fn();

      logger.info = jest.fn();

      logger.log = jest.fn();

      logger.warn = jest.fn();

      logger.success = jest.fn();

 

      console.error = jest.fn();

      console.info = jest.fn();

      console.log = jest.fn();

      console.warn = jest.fn();

 

      process.stdout.write = jest.fn();

      process.stderr.write = jest.fn();

 

      return () => {

        logger.error = originalLoggerError;

        logger.info = originalLoggerInfo;

        logger.log = originalLoggerLog;

        logger.warn = originalLoggerWarn;

        logger.success = originalLoggerSuccess;

 

        console.error = originalConsoleError;

        console.info = originalConsoleInfo;

        console.log = originalConsoleLog;

        console.warn = originalConsoleWarn;

 

        process.stdout.write = originalStdoutWrite;

        process.stderr.write = originalStderrWrite;

      };

    },

  };

};

Copy after login

What is happening here?

  1. The assignment

1

2

3

4

5

6

7

8

9

10

11

const originalLoggerError = logger.error;

const originalLoggerInfo = logger.info;

const originalLoggerLog = logger.log;

const originalLoggerWarn = logger.warn;

const originalLoggerSuccess = logger.success;

const originalConsoleError = console.error;

const originalConsoleInfo = console.info;

const originalConsoleLog = console.log;

const originalConsoleWarn = console.warn;

const originalStdoutWrite = process.stdout.write;

const originalStderrWrite = process.stderr.write;

Copy after login

2. Returns setup

If you noticed above, setup is called inside temporarilySilenceLogs, this is returned by createLogSilencer

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

return {

    setup() {

      logger.error = jest.fn();

      logger.info = jest.fn();

      logger.log = jest.fn();

      logger.warn = jest.fn();

      logger.success = jest.fn();

 

      console.error = jest.fn();

      console.info = jest.fn();

      console.log = jest.fn();

      console.warn = jest.fn();

 

      process.stdout.write = jest.fn();

      process.stderr.write = jest.fn();

 

      return () => {

        logger.error = originalLoggerError;

        logger.info = originalLoggerInfo;

        logger.log = originalLoggerLog;

        logger.warn = originalLoggerWarn;

        logger.success = originalLoggerSuccess;

 

        console.error = originalConsoleError;

        console.info = originalConsoleInfo;

        console.log = originalConsoleLog;

        console.warn = originalConsoleWarn;

 

        process.stdout.write = originalStdoutWrite;

        process.stderr.write = originalStderrWrite;

      };

    },

  };

Copy after login

What is happening in the setup function?

2.1 Loggers and console API are initialised to jest.fn()

1

2

3

4

5

6

7

8

9

10

11

logger.error = jest.fn();

logger.info = jest.fn();

logger.log = jest.fn();

logger.warn = jest.fn();

logger.success = jest.fn();

console.error = jest.fn();

console.info = jest.fn();

console.log = jest.fn();

console.warn = jest.fn();

process.stdout.write = jest.fn();

process.stderr.write = jest.fn();

Copy after login

This pretty much silences the logs since jest.fn() gets called when you use any logger, hence this is considerd as setup, an important step to silence your logs.

2.2 setUp returns original loggers

If you have noticed, the sequence of function calls are

a. const silencer = createLogSilencer();

b. const dispose = silencer.setup();

c. In the finally block.

1

2

3

4

5

try {

 await testFn();

} finally {

 dispose();

}

Copy after login

dispose is returned by setup function that is returned by createLogSilencer. This step restores the logging mechanism after executing your test function.

About us:

At Thinkthroo, we study large open source projects and provide architectural guides. We have developed reusable Components, built with tailwind, that you can use in your project. We offer Next.js, React and Node development services.

Book a meeting with us to discuss your project.

How to temporarily silence logs in tests

References:

  1. https://github.com/changesets/changesets/tree/main/packages/logger#silencing-messages-in-tests

  2. https://github.com/search?q=repo:changesets/changesets temporarilySilenceLogs &type=code

  3. https://github.com/changesets/changesets/blob/baf56448606e005577dbe2fb1e78ff457dcaaefd/scripts/test-utils/src/index.ts#L16

The above is the detailed content of How to temporarily silence logs in tests. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles