├── .gitignore ├── index.js ├── img ├── screenshot-problem.png ├── screenshot-solution.png └── screenshot-analyze-logs.jpg ├── .babelrc ├── CONTRIBUTORS.md ├── test ├── noMockConsole.test.ts ├── setupTestFramework.test.ts └── mockConsole.test.ts ├── .travis.yml ├── jest26.config.js ├── jest27.config.js ├── jest28.config.js ├── tsconfig.json ├── index.d.ts ├── src ├── index.js └── setupTestFramework.js ├── LICENSE ├── .vscode └── launch.json ├── dist ├── index.js └── setupTestFramework.js ├── package.json └── Readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | .npmrc 4 | node_modules 5 | **.tgz 6 | 7 | coverage -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const mockConsole = require('./dist/index').default; 2 | 3 | module.exports = mockConsole; 4 | -------------------------------------------------------------------------------- /img/screenshot-problem.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bpedersen/jest-mock-console/HEAD/img/screenshot-problem.png -------------------------------------------------------------------------------- /img/screenshot-solution.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bpedersen/jest-mock-console/HEAD/img/screenshot-solution.png -------------------------------------------------------------------------------- /img/screenshot-analyze-logs.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bpedersen/jest-mock-console/HEAD/img/screenshot-analyze-logs.jpg -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["@babel/preset-env", { 4 | "targets": { 5 | "node": "4.5" 6 | } 7 | }] 8 | ] 9 | } -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | jest-mock-console contributors (sorted alphabetically) 2 | ============================================ 3 | 4 | * **[Quentin Golsteyn](https://github.com/qgolsteyn)** 5 | 6 | * Added Typescript support -------------------------------------------------------------------------------- /test/noMockConsole.test.ts: -------------------------------------------------------------------------------- 1 | describe("not using the jest-mock-console", () => { 2 | it("should work", () => { 3 | expect(true).toBe(true); 4 | }); 5 | describe.skip("should skip this test", () => { 6 | it("should fail if executed", () => { 7 | throw new Error("This shouldn't be executed"); 8 | }); 9 | }); 10 | }); 11 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: true 2 | language: node_js 3 | cache: 4 | directories: 5 | - node_modules 6 | notifications: 7 | email: false 8 | node_js: 9 | - "10" 10 | - "12" 11 | - "14" 12 | - "15" 13 | 14 | script: 15 | - npm run test 16 | - npm run test:setupfile-with-circus 17 | - npm run test:setupfile-with-jasmine 18 | - npm run test26 19 | - npm run test26:with-setup 20 | after_success: 21 | - codecov 22 | branches: 23 | only: 24 | - master 25 | -------------------------------------------------------------------------------- /jest26.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | coverageDirectory: "./coverage/", 3 | collectCoverage: true, 4 | moduleNameMapper: { 5 | "jest-mock-console": "/src", 6 | }, 7 | transform: { 8 | "^.+\\.jsx?$": "babel-jest", 9 | "^.+\\.tsx?$": "ts-jest26", 10 | }, 11 | testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", 12 | testURL: "http://localhost", 13 | moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], 14 | }; 15 | -------------------------------------------------------------------------------- /jest27.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | coverageDirectory: "./coverage/", 3 | collectCoverage: true, 4 | moduleNameMapper: { 5 | "jest-mock-console": "/src", 6 | }, 7 | transform: { 8 | "^.+\\.jsx?$": "babel-jest", 9 | "^.+\\.tsx?$": "ts-jest27", 10 | }, 11 | testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", 12 | testURL: "http://localhost", 13 | moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], 14 | }; 15 | -------------------------------------------------------------------------------- /jest28.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | coverageDirectory: "./coverage/", 3 | collectCoverage: true, 4 | moduleNameMapper: { 5 | "jest-mock-console": "/src", 6 | }, 7 | transform: { 8 | "^.+\\.jsx?$": "babel-jest", 9 | "^.+\\.tsx?$": "ts-jest", 10 | }, 11 | testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", 12 | testEnvironmentOptions: { 13 | url: "http://localhost", 14 | }, 15 | moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], 16 | }; 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "lib": [ 5 | "es6", 6 | "dom" 7 | ], 8 | "noImplicitAny": true, 9 | "noImplicitThis": true, 10 | "strictNullChecks": true, 11 | "strictFunctionTypes": true, 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "noEmit": true, 16 | "forceConsistentCasingInFileNames": true, 17 | "paths": { 18 | "jest-mock-console": ["./"] 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for jest-mock-console 0.3.7 2 | // Project: jest-mock-console 3 | // Definitions by: Quentin Golsteyn https://github.com/qgolsteyn 4 | 5 | type DefaultConsole = Console; 6 | type ConsoleProps = keyof DefaultConsole; 7 | 8 | declare module 'jest-mock-console' { 9 | export default function MockConsole(): RestoreConsole; 10 | export default function MockConsole(mockArg: ConsoleProps): RestoreConsole; 11 | export default function MockConsole(mockArg: ConsoleProps[]): RestoreConsole; 12 | export default function MockConsole(mockArg: MockObj): RestoreConsole; 13 | 14 | type MockObj = {[key in ConsoleProps]?: DefaultConsole[key]}; 15 | type RestoreConsole = () => void; 16 | } -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | const defaultKeys = ["log", "warn", "error"]; 2 | 3 | if (!describe) { 4 | require("@jest/globals"); 5 | } 6 | 7 | const mockConsole = (mockArg) => { 8 | const originalConsole = { ...console }; 9 | // No argument 10 | if (!mockArg) { 11 | defaultKeys.forEach((key) => { 12 | global.console[key] = jest.fn(); 13 | }); 14 | } 15 | // Argument is a string 16 | else if (typeof mockArg === "string" || mockArg instanceof String) { 17 | global.console[mockArg] = jest.fn(); 18 | } 19 | // Argument is an array 20 | else if (Array.isArray(mockArg)) { 21 | mockArg.forEach((key) => { 22 | global.console[key] = jest.fn(); 23 | }); 24 | } 25 | // Argument is an object 26 | else { 27 | Object.keys(mockArg).forEach((key) => { 28 | global.console[key] = mockArg[key]; 29 | }); 30 | } 31 | // Return function to restore console 32 | return () => { 33 | global.console = originalConsole; 34 | }; 35 | }; 36 | 37 | export default mockConsole; 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Brian Pedersen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Debug Jasmine SetupTestFramework", 9 | "type": "node", 10 | "request": "launch", 11 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/jest", 12 | "args": [ 13 | "test", 14 | "--runInBand", 15 | "--no-cache", 16 | "--watchAll=false", 17 | "--setupTestFrameworkScriptFile=./src/setupTestFramework.js", 18 | "--testNamePattern=setupTestFramework", 19 | "--testRunner=jest-jasmine2", 20 | "${fileBasenameNoExtension}" 21 | ], 22 | "cwd": "${workspaceRoot}", 23 | "protocol": "inspector", 24 | "console": "integratedTerminal", 25 | "internalConsoleOptions": "neverOpen", 26 | "env": { "CI": "true" }, 27 | "disableOptimisticBPs": true 28 | }, 29 | { 30 | "name": "Debug Circus SetupTestFramework", 31 | "type": "node", 32 | "request": "launch", 33 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/jest", 34 | "args": [ 35 | "test", 36 | "--runInBand", 37 | "--no-cache", 38 | "--watchAll=false", 39 | "--setupTestFrameworkScriptFile=./src/setupTestFramework.js", 40 | "--testNamePattern=setupTestFramework", 41 | "${fileBasenameNoExtension}" 42 | ], 43 | "cwd": "${workspaceRoot}", 44 | "protocol": "inspector", 45 | "console": "integratedTerminal", 46 | "internalConsoleOptions": "neverOpen", 47 | "env": { "CI": "true" }, 48 | "disableOptimisticBPs": true 49 | } 50 | ] 51 | } 52 | -------------------------------------------------------------------------------- /src/setupTestFramework.js: -------------------------------------------------------------------------------- 1 | // Check to see if version before 27 where jasmine is default 2 | if (global.jasmine) { 3 | const originalDescribe = jasmine.getEnv().describe; 4 | 5 | jasmine.getEnv().describe = ( 6 | description, 7 | specDefinitions, 8 | ...describeArgs 9 | ) => { 10 | let $jestMockConsoleEachOriginal; 11 | let $jestMockConsoleAllOriginal; 12 | const injectedSpecDefinition = (...specArgs) => { 13 | beforeEach(() => { 14 | $jestMockConsoleEachOriginal = { ...console }; 15 | }); 16 | afterEach(() => { 17 | global.console = $jestMockConsoleEachOriginal; 18 | }); 19 | beforeAll(() => { 20 | $jestMockConsoleAllOriginal = { ...console }; 21 | }); 22 | afterAll(() => { 23 | global.console = $jestMockConsoleAllOriginal; 24 | }); 25 | specDefinitions(...specArgs); 26 | }; 27 | return originalDescribe( 28 | description, 29 | injectedSpecDefinition, 30 | ...describeArgs 31 | ); 32 | }; 33 | } else { 34 | const originalDescribe = describe; 35 | 36 | const decorateDescribe = (describeFn) => (description, specDefinitions) => { 37 | let $jestMockConsoleEachOriginal; 38 | let $jestMockConsoleAllOriginal; 39 | 40 | const injectedSpecDefinition = (...specArgs) => { 41 | beforeEach(() => { 42 | $jestMockConsoleEachOriginal = { ...console }; 43 | }); 44 | afterEach(() => { 45 | global.console = $jestMockConsoleEachOriginal; 46 | }); 47 | beforeAll(() => { 48 | $jestMockConsoleAllOriginal = { ...console }; 49 | }); 50 | afterAll(() => { 51 | global.console = $jestMockConsoleAllOriginal; 52 | }); 53 | return specDefinitions(...specArgs); 54 | }; 55 | return describeFn(description, injectedSpecDefinition); 56 | }; 57 | 58 | global.describe = decorateDescribe(originalDescribe); 59 | global.describe.skip = decorateDescribe(originalDescribe.skip); 60 | global.describe.only = decorateDescribe(originalDescribe.only); 61 | global.describe.each = (table) => 62 | decorateDescribe(originalDescribe.each(table)); 63 | } 64 | -------------------------------------------------------------------------------- /test/setupTestFramework.test.ts: -------------------------------------------------------------------------------- 1 | import mockConsole from "jest-mock-console"; 2 | 3 | const originalConsole = { ...console }; 4 | 5 | describe("setupTestFramework", () => { 6 | const logMock = (string: string) => string; 7 | console.log = logMock; 8 | describe("should reset console between it blocks", () => { 9 | it("is the first block", () => { 10 | mockConsole("log"); 11 | console.log("Will not show"); 12 | expect(console.log).toHaveBeenCalledWith("Will not show"); 13 | }); 14 | it("is the second block", () => { 15 | // Checks if the describe block has been modified 16 | if (global.jasmine) { 17 | if ( 18 | jasmine 19 | // @ts-expect-error 20 | .getEnv() 21 | .describe.toString() 22 | .indexOf("$jestMockConsoleEachOriginal") !== -1 23 | ) { 24 | expect(console.log).toBe(logMock); 25 | } else { 26 | expect(console.log).not.toBe(logMock); 27 | } 28 | } else { 29 | if ( 30 | describe.toString().indexOf("$jestMockConsoleEachOriginal") !== -1 31 | ) { 32 | expect(console.log).toBe(logMock); 33 | } else { 34 | expect(console.log).not.toBe(logMock); 35 | } 36 | } 37 | }); 38 | }); 39 | describe("should work with beforeAll", () => { 40 | beforeAll(() => { 41 | mockConsole(); 42 | }); 43 | it("test 1", () => { 44 | console.log("Will not show"); 45 | expect(console.log).toHaveBeenCalledWith("Will not show"); 46 | }); 47 | it("test 2", () => { 48 | console.log("Will not show"); 49 | expect(console.log).toHaveBeenCalledWith("Will not show"); 50 | }); 51 | }); 52 | describe.skip("should skip this test", () => { 53 | it("should fail if executed", () => { 54 | throw new Error("This shouldn't be executed"); 55 | }); 56 | }); 57 | describe.each([1, 2])("should work with .each", () => { 58 | it("test 1", () => { 59 | mockConsole(); 60 | console.log("Will not show"); 61 | expect(console.log).toHaveBeenCalledWith("Will not show"); 62 | }); 63 | }); 64 | }); 65 | -------------------------------------------------------------------------------- /dist/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | Object.defineProperty(exports, "__esModule", { 4 | value: true 5 | }); 6 | exports.default = void 0; 7 | 8 | function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } 9 | 10 | function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 11 | 12 | function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 13 | 14 | var defaultKeys = ['log', 'warn', 'error']; 15 | 16 | var mockConsole = function mockConsole(mockArg) { 17 | var originalConsole = _objectSpread({}, console); // No argument 18 | 19 | 20 | if (!mockArg) { 21 | defaultKeys.forEach(function (key) { 22 | global.console[key] = jest.fn(); 23 | }); 24 | } // Argument is a string 25 | else if (typeof mockArg === 'string' || mockArg instanceof String) { 26 | global.console[mockArg] = jest.fn(); 27 | } // Argument is an array 28 | else if (Array.isArray(mockArg)) { 29 | mockArg.forEach(function (key) { 30 | global.console[key] = jest.fn(); 31 | }); 32 | } // Argument is an object 33 | else { 34 | Object.keys(mockArg).forEach(function (key) { 35 | global.console[key] = mockArg[key]; 36 | }); 37 | } // Return function to restore console 38 | 39 | 40 | return function () { 41 | global.console = originalConsole; 42 | }; 43 | }; 44 | 45 | var _default = mockConsole; 46 | exports.default = _default; -------------------------------------------------------------------------------- /dist/setupTestFramework.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } 4 | 5 | function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } 6 | 7 | function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 8 | 9 | // Check to see if version before 27 where jasmine is default 10 | if (global.jasmine) { 11 | var originalDescribe = jasmine.getEnv().describe; 12 | 13 | jasmine.getEnv().describe = function (description, specDefinitions) { 14 | var $jestMockConsoleOriginal; 15 | 16 | var injectedSpecDefinition = function injectedSpecDefinition() { 17 | beforeEach(function () { 18 | $jestMockConsoleOriginal = _objectSpread({}, console); 19 | }); 20 | afterEach(function () { 21 | global.console = $jestMockConsoleOriginal; 22 | }); 23 | specDefinitions.apply(void 0, arguments); 24 | }; 25 | 26 | for (var _len = arguments.length, describeArgs = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { 27 | describeArgs[_key - 2] = arguments[_key]; 28 | } 29 | 30 | return originalDescribe.apply(void 0, [description, injectedSpecDefinition].concat(describeArgs)); 31 | }; 32 | } else { 33 | var _originalDescribe = describe; 34 | 35 | describe = function describe(description, specDefinitions) { 36 | var $jestMockConsoleOriginal; 37 | 38 | var injectedSpecDefinition = function injectedSpecDefinition() { 39 | beforeEach(function () { 40 | $jestMockConsoleOriginal = _objectSpread({}, console); 41 | }); 42 | afterEach(function () { 43 | global.console = $jestMockConsoleOriginal; 44 | }); 45 | return specDefinitions.apply(void 0, arguments); 46 | }; 47 | 48 | return _originalDescribe(description, injectedSpecDefinition); 49 | }; 50 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jest-mock-console", 3 | "version": "1.3.0", 4 | "description": "Jest utility to mock the console", 5 | "main": "index.js", 6 | "types": "index.d.ts", 7 | "scripts": { 8 | "build": "babel src -d dist", 9 | "jest26": "node ./node_modules/jest26/bin/jest --config=jest26.config.js", 10 | "jest27": "node ./node_modules/jest27/bin/jest --config=jest27.config.js", 11 | "jest": "node ./node_modules/jest/bin/jest --config=jest28.config.js", 12 | "test:no-mock-console": "node ./node_modules/jest/bin/jest --testPathPattern=noMockConsole", 13 | "test": "npm run jest --coverage --collectCoverageFrom=src/index.js", 14 | "test:watch": "npm run jest --watch", 15 | "test:setupfile-with-circus": "npm run jest27 -- --setupTestFrameworkScriptFile=./src/setupTestFramework.js --coverage --collectCoverageFrom=src/**.js", 16 | "test:setupfile-with-jasmine": "npm run jest27 --setupTestFrameworkScriptFile=./src/setupTestFramework.js --coverage --collectCoverageFrom=src/**.js --testRunner=jest-jasmine2", 17 | "test26": "npm run jest26 -- --coverage --collectCoverageFrom=src/index.js", 18 | "test26:with-setup": "npm run jest26 -- --setupTestFrameworkScriptFile=./src/setupTestFramework.js --coverage --collectCoverageFrom=src/**.js", 19 | "test27": "npm run jest27 -- --coverage --collectCoverageFrom=src/index.js", 20 | "test27:with-setup": "npm run jest27 -- --setupTestFrameworkScriptFile=./src/setupTestFramework.js --coverage --collectCoverageFrom=src/**.js" 21 | }, 22 | "files": [ 23 | "dist", 24 | "index.d.ts", 25 | "index.js" 26 | ], 27 | "author": "Brian H Pedersen", 28 | "contributors": [ 29 | "Quentin Golsteyn", 30 | "NoriSte" 31 | ], 32 | "license": "MIT", 33 | "peerDependencies": { 34 | "jest": ">= 22.4.2" 35 | }, 36 | "devDependencies": { 37 | "@babel/cli": "^7.13.16", 38 | "@babel/core": "^7.13.16", 39 | "@babel/preset-env": "^7.13.15", 40 | "@types/jest": "^26.0.22", 41 | "babel-jest": "^26.6.3", 42 | "codecov": "^3.0.0", 43 | "jest": "^28.0.3", 44 | "jest26": "npm:jest@^26.6.3", 45 | "jest27": "npm:jest@^27.2.4", 46 | "ts-jest": "^28.0.3", 47 | "ts-jest26": "npm:ts-jest@^26.5.6", 48 | "ts-jest27": "npm:ts-jest@^27.1.5", 49 | "typescript": "^4.2.4" 50 | }, 51 | "publishConfig": { 52 | "registry": "https://registry.npmjs.org/" 53 | }, 54 | "repository": { 55 | "type": "git", 56 | "url": "https://github.com/bpedersen/jest-mock-console.git" 57 | }, 58 | "bugs": { 59 | "url": "https://github.com/bpedersen/jest-mock-console/issues" 60 | }, 61 | "homepage": "https://github.com/bpedersen/jest-mock-console#readme", 62 | "jest": { 63 | "coverageDirectory": "./coverage/", 64 | "collectCoverage": true, 65 | "moduleNameMapper": { 66 | "jest-mock-console": "/src" 67 | }, 68 | "transform": { 69 | "^.+\\.jsx?$": "babel-jest", 70 | "^.+\\.tsx?$": "ts-jest" 71 | }, 72 | "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", 73 | "testURL": "http://localhost", 74 | "moduleFileExtensions": [ 75 | "ts", 76 | "tsx", 77 | "js", 78 | "jsx", 79 | "json", 80 | "node" 81 | ] 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /test/mockConsole.test.ts: -------------------------------------------------------------------------------- 1 | import mockConsole, { RestoreConsole } from "jest-mock-console"; 2 | 3 | describe("mockConsole", () => { 4 | console.log = jest.fn(() => { 5 | throw "Log called"; 6 | }); 7 | console.warn = jest.fn(() => { 8 | throw "Warn called"; 9 | }); 10 | console.error = jest.fn(() => { 11 | throw "Error called"; 12 | }); 13 | 14 | describe("no arguments", () => { 15 | it("should prevent original function while mocked", () => { 16 | const restore = mockConsole(); 17 | console.error("This should not display"); 18 | expect(console.error).toHaveBeenCalledWith("This should not display"); 19 | expect(console.error).not.toThrow(); 20 | restore(); 21 | }); 22 | it("should restore the console as it was before the mock", () => { 23 | const restore = mockConsole(); 24 | expect(console.error).not.toThrow(); 25 | restore(); 26 | expect(console.error).toThrowError("Error called"); 27 | }); 28 | }); 29 | describe("a string", () => { 30 | it("should mock only string key", () => { 31 | const restore = mockConsole("error"); 32 | console.error("This should not display"); 33 | expect(console.error).toHaveBeenCalledWith("This should not display"); 34 | expect(console.error).not.toThrow(); 35 | expect(console.log).toThrowError("Log called"); 36 | restore(); 37 | }); 38 | it("should restore the console as it was before the mock", () => { 39 | const originalConsole = { ...console }; 40 | const restore = mockConsole("error"); 41 | expect(console).not.toEqual(originalConsole); 42 | restore(); 43 | expect(console).toEqual(originalConsole); 44 | }); 45 | }); 46 | describe("an array", () => { 47 | it("should mock only keys in the array", () => { 48 | const restore = mockConsole(["error", "warn"]); 49 | console.error("This should not display"); 50 | console.warn("This also should not display"); 51 | expect(console.error).toHaveBeenCalledWith("This should not display"); 52 | expect(console.warn).toHaveBeenCalledWith("This also should not display"); 53 | expect(console.error).not.toThrow(); 54 | expect(console.warn).not.toThrow(); 55 | expect(console.log).toThrowError("Log called"); 56 | restore(); 57 | }); 58 | it("should restore the console as it was before the mock", () => { 59 | const originalConsole = { ...console }; 60 | const restore = mockConsole(["error", "warn"]); 61 | expect(console).not.toEqual(originalConsole); 62 | restore(); 63 | expect(console).toEqual(originalConsole); 64 | }); 65 | }); 66 | describe("an object", () => { 67 | it("should mock console with object passed", () => { 68 | const restore = mockConsole({ 69 | error: (s: string) => s, 70 | warn: (s: string) => s, 71 | }); 72 | expect(console.error("This should not display")).toEqual( 73 | "This should not display" 74 | ); 75 | expect(console.warn("This also should not display")).toEqual( 76 | "This also should not display" 77 | ); 78 | expect(console.error).not.toThrow(); 79 | expect(console.warn).not.toThrow(); 80 | expect(console.log).toThrowError("Log called"); 81 | restore(); 82 | }); 83 | it("should restore the console as it was before the mock", () => { 84 | const originalConsole = { ...console }; 85 | const restore = mockConsole({ 86 | error: (s: string) => s, 87 | warn: (s: string) => s, 88 | }); 89 | expect(console).not.toEqual(originalConsole); 90 | restore(); 91 | expect(console).toEqual(originalConsole); 92 | }); 93 | }); 94 | describe("should work with beforeAll", () => { 95 | let restore: RestoreConsole; 96 | beforeAll(() => { 97 | restore = mockConsole({ 98 | log: (s: string) => s, 99 | error: (s: string) => s, 100 | warn: (s: string) => s, 101 | }); 102 | }); 103 | afterAll(() => { 104 | restore(); 105 | }); 106 | it("should mock this", () => { 107 | expect(console.log("This should not display")).toEqual( 108 | "This should not display" 109 | ); 110 | }); 111 | }); 112 | describe.skip("should skip this test", () => { 113 | it("should fail if executed", () => { 114 | throw new Error("This shouldn't be executed"); 115 | }); 116 | }); 117 | }); 118 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # jest-mock-console 2 | 3 | Jest utility to mock the console 4 | 5 | [![codecov][codecov-badge]][codecov] 6 | [![build][build-badge]][build] 7 | [![Dependencies][dependencyci-badge]][dependencyci] 8 | [![MIT License][license-badge]][license] 9 | 10 | ## Table of Contents 11 | 12 | - [Problem](#the-problem) 13 | - [Solution](#the-solution) 14 | - [Installation](#installation) 15 | - [Basic Example](#basic-example) 16 | - [Advanced Example](#advanced-example) 17 | - [Analyze all logs](#analyze-all-logs) 18 | - [mockConsole(mocks)](#mockconsolemocks) 19 | - [default](#mock-default) 20 | - [string](#mock-string) 21 | - [array](#mock-array) 22 | - [object](#mock-object) 23 | 24 | ## The problem 25 | 26 | If you use console or prop-types in your app, and you use jest then you end up with tests that look like: 27 | 28 | Terminal Screenshot 34 | 35 | This is not helpful as all of the tests have passed, but you are seeing red. It is especially unhelpful when there is an actual failure as you have to search through all the red to find the actual failed test. 36 | 37 | ## The solution 38 | 39 | This allows you to mock and unmock the console at will, so your tests look like: 40 | 41 | Terminal Screenshot 47 | 48 | This is much more helpful as you don't see red on success anymore. Then you know when you see red text you know something went wrong. 49 | 50 | ## Installation 51 | 52 | This module is distributed view [npm][npm] which is bundled with [node][node] and should be installed as one of your project's `devDependencies`: 53 | 54 | ``` 55 | npm install --save-dev jest-mock-console 56 | ``` 57 | 58 | ## Basic Example 59 | 60 | At the top of your test file: 61 | 62 | ```javascript 63 | import mockConsole from "jest-mock-console"; 64 | ``` 65 | 66 | Then your tests 67 | 68 | ```javascript 69 | describe(... 70 | it(... 71 | const restoreConsole = mockConsole(); // mockConsole returns a function to restore it back to normal 72 | console.error('This will not show in the test report'); 73 | expect(console.error).toHaveBeenCalled(); 74 | restoreConsole(); 75 | ) 76 | ) 77 | ``` 78 | 79 | However you always need to restore the console after each test or you will break jest. This is where the [setupTestFramework](#setuptestframework) file comes in. 80 | 81 | ## Advanced Example 82 | 83 | If you don't want to worry about accidentally forgetting to `restoreConsole()` after your tests you can modify jest to unmock after every `it(...)`. 84 | 85 | In your jest config: 86 | 87 | ```javascript 88 | setupFilesAfterEnv: ["jest-mock-console/dist/setupTestFramework.js"]; 89 | ``` 90 | 91 | Then in your test files: 92 | 93 | ```javascript 94 | import mockConsole from 'jest-mock-console'; 95 | 96 | describe(... 97 | it(... 98 | mockConsole(); 99 | console.error('This will not show in the test report'); 100 | expect(console.error).toHaveBeenCalled(); 101 | // No need for restoreConsole as it is called after every `it(...)` 102 | ) 103 | ) 104 | ``` 105 | 106 | ## Analyze all logs 107 | 108 | In some circumstances Jest is infamous for logging because it overwrites the bash output. If you're experiencing this kind of logging frustration and you need to analyze all the `console.log` call arguments (typically to understand why a test is failing) you can temporarily add an expect statement on the console itself. 109 | 110 | In your test files: 111 | 112 | ```javascript 113 | describe(... 114 | it(... 115 | const restoreConsole = mockConsole(); 116 | console.error('This will not show in the test report'); 117 | expect(console.error.mock.calls).toEqual([]); 118 | restoreConsole(); 119 | ) 120 | ) 121 | ``` 122 | 123 | the test looks like: 124 | 125 | Terminal Screenshot 131 | 132 | ## mockConsole(mocks) 133 | 134 | - **`mocks[string,array,object]`**: The properties of the console you want to mock. Defaults to ['log','warn','error'] 135 | - default - Will mock console.log, console.warn, and console.error 136 | ``` 137 | mockConsole() // same as `mockConsole(['log','warn','error']) 138 | ``` 139 | - string - You can mock a single function 140 | ``` 141 | mockConsole('error') 142 | ``` 143 | - array - You can mock multiple functions 144 | ``` 145 | mockConsole(['log', 'info']) 146 | ``` 147 | - object - You can set custom functions for console 148 | ``` 149 | const originalConsole = window.console; 150 | mockConsole({ 151 | error: (...args) => originalConsole.log(`console.error of: ${...args}`) 152 | }) 153 | ``` 154 | 155 | ## LICENSE 156 | 157 | MIT 158 | 159 | [npm]: https://www.npmjs.com/ 160 | [node]: https://nodejs.org/ 161 | [codecov-badge]: https://codecov.io/gh/bpedersen/jest-mock-console/branch/master/graph/badge.svg 162 | [codecov]: https://codecov.io/gh/bpedersen/jest-mock-console 163 | [build-badge]: https://travis-ci.org/bpedersen/jest-mock-console.svg 164 | [build]: https://travis-ci.org/bpedersen/jest-mock-console 165 | [dependencyci-badge]: https://dependencyci.com/github/bpedersen/jest-mock-console/badge 166 | [dependencyci]: https://dependencyci.com/github/bpedersen/jest-mock-console 167 | [license-badge]: https://img.shields.io/npm/l/jest-mock-console.svg 168 | [license]: https://github.com/bpedersen/jest-mock-console/blob/master/other/LICENSE 169 | --------------------------------------------------------------------------------