Jest: best way to disable console inside unit tests

I wonder if there is a better way to disable console errors inside a specific Jest test (i.e. restore the original console before / after each test).

Here is my current approach:

describe("Some description", () => {
  let consoleSpy;

  beforeEach(() => {
    if (typeof consoleSpy === "function") {
      consoleSpy.mockRestore();
    }
  });

  test("Some test that should not output errors to jest console", () => {
    expect.assertions(2);

    consoleSpy = jest.spyOn(console, "error").mockImplementation();

    // some function that uses console error
    expect(someFunction).toBe("X");
    expect(consoleSpy).toHaveBeenCalled();
  });

  test("Test that has console available", () => {
    // shows up during jest watch test, just as intended
    console.error("test");
  });
});

Is there a cleaner way to do the same? I would like to avoid spyOn, but mockRestoreonly works with it .

Thank!

+34
source share
5 answers

, , .

console.log = jest.fn()
expect(console.log).toHaveBeenCalled();
+32

. console.log console.log ,

jest --silent

( )

warn, info and debug

__tests __/setup.js

global.console = {
    log: jest.fn()
}

jest.config.js

module.exports = {
    verbose: true,
    setupTestFrameworkScriptFile: "<rootDir>/__tests__/setup.js",
};

Jest v24.x : setupTestFrameworkScriptFile setupFilesAfterEnv.

module.exports = {
    verbose: true,
    setupFilesAfterEnv: ["<rootDir>/__tests__/setup.js"],
};
+32

, : console.log console (, warn, error), console.

22+:

package.json

"jest": {
  "setupFiles": [...],
  "setupTestFrameworkScriptFile": "<rootDir>/jest/setup.js",
  ...
}

JEST/setup.js

jest.spyOn(global.console, 'log').mockImplementation(() => jest.fn());

console.log console.log console .

+13

/ ( jest API, , ), , mockRestore:

// at start of test you want to suppress
const consoleLog = console.log;
console.log = jest.fn();

// at end of test
console.log = consoleLog;
+3

process.env.NODE_ENV. , , ( ) :

if (process.env.NODE_ENV === 'development') {
  console.log('Show output only while in "development" mode');
} else if (process.env.NODE_ENV === 'test') {
  console.log('Show output only while in "test" mode');
}

const logDev = msg => {
  if (process.env.NODE_ENV === 'development') {
    console.log(msg);
  }
}
logDev('Show output only while in "development" mode');

package.json:

"jest": {
  "globals": {
    "NODE_ENV": "test"
  }
}

, , , console.log .

+1
source

Source: https://habr.com/ru/post/1678917/


All Articles