├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── settings.yml ├── .gitignore ├── .prettierrc ├── .release-it.json ├── LICENSE ├── README.md ├── circle.yml ├── jest.config.js ├── package.json ├── src ├── index.d.ts └── index.js └── tsconfig.json /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 4 | 5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion. 6 | 7 | Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. 8 | 9 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. 10 | 11 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. 12 | 13 | This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/) 14 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are welcome and will be fully credited! 4 | 5 | We accept contributions via Pull Requests on [Github](https://github.com/{{ githubAccount }}/{{ name }}). 6 | 7 | ## Pull Requests 8 | 9 | Here are some guidelines to make the process smoother: 10 | 11 | - **Add a test** - New features and bugfixes need tests. If you find it difficult to test, please tell us in the pull request and we will try to help you! 12 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 13 | - **Run `npm test` locally** - This will allow you to go faster 14 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 15 | - **Send coherent history** - Make sure your commits message means something 16 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 17 | 18 | ## Creating issues 19 | 20 | ### Bug reports 21 | 22 | Always try to provide as much information as possible. If you are reporting a bug, try to provide a repro on jsfiddle.net (or anything else) or a stacktrace at the very least. This will help us check the problem quicker. 23 | 24 | ### Feature requests 25 | 26 | Lay out the reasoning behind it and propose an API for it. Ideally, you should have a practical example to prove the utility of the feature you're requesting. 27 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 9 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | **What kind of change does this PR introduce?** (check at least one) 10 | 11 | - [ ] Bugfix 12 | - [ ] Feature 13 | - [ ] Code style update 14 | - [ ] Refactor 15 | - [ ] Build-related changes 16 | - [ ] Other, please describe: 17 | 18 | **Does this PR introduce a breaking change?** (check one) 19 | 20 | - [ ] Yes 21 | - [ ] No 22 | 23 | If yes, please describe the impact and migration path for existing applications: 24 | 25 | **The PR fulfills these requirements:** 26 | 27 | - [ ] When resolving a specific issue, it's referenced in the PR's title (e.g. `fix #xxx[,#xxx]`, where "xxx" is the issue number) 28 | - [ ] All tests are passing 29 | - [ ] New/updated tests are included 30 | 31 | If adding a **new feature**, the PR's description includes: 32 | 33 | - [ ] A convincing reason for adding this feature (to avoid wasting your time, it's best to open a suggestion issue first and wait for approval before working on it) 34 | 35 | **Other information:** 36 | -------------------------------------------------------------------------------- /.github/settings.yml: -------------------------------------------------------------------------------- 1 | labels: 2 | - name: bug 3 | color: ee0701 4 | - name: contribution welcome 5 | color: 0e8a16 6 | - name: discussion 7 | color: 4935ad 8 | - name: docs 9 | color: 8be281 10 | - name: enhancement 11 | color: a2eeef 12 | - name: good first issue 13 | color: 7057ff 14 | - name: help wanted 15 | color: 008672 16 | - name: question 17 | color: d876e3 18 | - name: wontfix 19 | color: ffffff 20 | - name: WIP 21 | color: ffffff 22 | - name: need repro 23 | color: c9581c 24 | - name: feature request 25 | color: fbca04 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | npm-debug.log 4 | yarn-error.log 5 | .nyc_output 6 | coverage.lcov 7 | dist 8 | package-lock.json 9 | yarn.lock 10 | .DS_Store 11 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "trailingComma": "es5", 4 | "singleQuote": true 5 | } 6 | -------------------------------------------------------------------------------- /.release-it.json: -------------------------------------------------------------------------------- 1 | { 2 | "src": { 3 | "tagName": "v%s", 4 | "commitMessage": "chore(release): %s" 5 | }, 6 | "github": { 7 | "release": true, 8 | "releaseName": "🚀 Release %s", 9 | "tokenRef": "GITHUB_TOKEN" 10 | }, 11 | "npm": { 12 | "publish": true 13 | }, 14 | "changelogCommand": "git log --pretty=format:'* %s (%h)' [REV_RANGE]" 15 | } 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Evan You, Eduardo San Martin Morote 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jest-mock-warn [![npm package](https://badgen.net/npm/v/jest-mock-warn)](https://www.npmjs.com/package/jest-mock-warn) 2 | 3 | > mock `console.warn` 4 | 5 | ## Installation 6 | 7 | ```sh 8 | yarn add -D jest-mock-warn 9 | ``` 10 | 11 | ## Usage 12 | 13 | ```js 14 | import { mockWarn } from 'jest-mock-warn' 15 | 16 | function myFunction() { 17 | if (!arguments.length) console.warn('provide an argument') 18 | } 19 | 20 | describe('my tests', () => { 21 | mockWarn() 22 | it('warns when called without arguments', () => { 23 | myFunction() 24 | expect('provide an argument').toHaveBeenWarned() 25 | expect('provide an argument').toHaveBeenWarnedTimes(1) 26 | expect('provide an argument').toHaveBeenLastWarned() 27 | }) 28 | }) 29 | ``` 30 | 31 | ## API 32 | 33 | - `toHaveBeenWarned()` 34 | - `toHaveBeenWarnedLast()` 35 | - `toHaveBeenWarnedTimes(n: number)` 36 | 37 | ## License 38 | 39 | [MIT](http://opensource.org/licenses/MIT) 40 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | jobs: 4 | build: 5 | docker: 6 | - image: circleci/node:10 7 | 8 | working_directory: ~/repo 9 | 10 | steps: 11 | - checkout 12 | 13 | - restore_cache: 14 | keys: 15 | - dependencies-cache-{{ checksum "yarn.lock" }} 16 | - dependencies-cache- 17 | 18 | - run: yarn install 19 | 20 | - save_cache: 21 | paths: 22 | - node_modules 23 | key: dependencies-cache-{{ checksum "yarn.lock" }} 24 | 25 | - run: yarn run test 26 | 27 | - run: 28 | name: Send code coverage 29 | command: yarn codecov 30 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | collectCoverage: true, 3 | collectCoverageFrom: [ 4 | '/src/*.js', 5 | ], 6 | moduleFileExtensions: ['js', 'jsx', 'json', 'vue'], 7 | transform: { 8 | '^.+\\.jsx?$': 'babel-jest', 9 | // ".*\\.(vue)$": "vue-jest", 10 | }, 11 | moduleNameMapper: { 12 | '^@/(.*)$': '/src/$1', 13 | }, 14 | coveragePathIgnorePatterns: [ 15 | '/test/*.js', 16 | '/test/.*.js', 17 | '/test/*/*.js', 18 | ], 19 | testURL: 'http://localhost/', 20 | } 21 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jest-mock-warn", 3 | "version": "1.1.0", 4 | "description": "Assert console.warn calls", 5 | "main": "src/index.js", 6 | "types": "src/index.d.ts", 7 | "author": { 8 | "name": "Eduardo San Martin Morote", 9 | "email": "posva13@gmail.com" 10 | }, 11 | "scripts": { 12 | "lint": "prettier -c \"{src,__tests__,e2e}/**/*.[jt]s?(x)\"", 13 | "test": "npm run lint" 14 | }, 15 | "files": [ 16 | "src", 17 | "LICENSE", 18 | "README.md" 19 | ], 20 | "keywords": [ 21 | "jest", 22 | "test", 23 | "warn", 24 | "mock", 25 | "utils" 26 | ], 27 | "license": "MIT", 28 | "devDependencies": { 29 | "jest": "^26.0.1", 30 | "prettier": "^1.19.1", 31 | "typescript": "^3.7.5" 32 | }, 33 | "repository": { 34 | "type": "git", 35 | "url": "git+https://github.com/posva/jest-mock-warn.git" 36 | }, 37 | "bugs": { 38 | "url": "https://github.com/posva/jest-mock-warn/issues" 39 | }, 40 | "homepage": "https://github.com/posva/jest-mock-warn#readme" 41 | } 42 | -------------------------------------------------------------------------------- /src/index.d.ts: -------------------------------------------------------------------------------- 1 | declare global { 2 | namespace jest { 3 | interface Matchers { 4 | toHaveBeenWarned(): R 5 | toHaveBeenWarnedLast(): R 6 | toHaveBeenWarnedTimes(n: number): R 7 | } 8 | } 9 | } 10 | 11 | export declare function mockWarn(): void 12 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | exports.mockWarn = function mockWarn() { 2 | expect.extend({ 3 | /** 4 | * 5 | * @param {string | RegExp} received 6 | */ 7 | toHaveBeenWarned(received) { 8 | asserted.set(received.toString(), received) 9 | const passed = warn.mock.calls.some(args => 10 | typeof received === 'string' 11 | ? args[0].indexOf(received) > -1 12 | : received.test(args[0]) 13 | ) 14 | if (passed) { 15 | return { 16 | pass: true, 17 | message: () => `expected "${received}" not to have been warned.`, 18 | } 19 | } else { 20 | const msgs = warn.mock.calls.map(args => args[0]).join('\n - ') 21 | return { 22 | pass: false, 23 | message: () => 24 | `expected "${received}" to have been warned.\n\nActual messages:\n\n - ${msgs}`, 25 | } 26 | } 27 | }, 28 | 29 | /** 30 | * 31 | * @param {string | RegExp} received 32 | */ 33 | toHaveBeenWarnedLast(received) { 34 | asserted.set(received.toString(), received) 35 | const lastCall = warn.mock.calls[warn.mock.calls.length - 1][0] 36 | const passed = 37 | typeof received === 'string' 38 | ? lastCall.indexOf(received) > -1 39 | : received.test(lastCall) 40 | if (passed) { 41 | return { 42 | pass: true, 43 | message: () => `expected "${received}" not to have been warned last.`, 44 | } 45 | } else { 46 | const msgs = warn.mock.calls.map(args => args[0]).join('\n - ') 47 | return { 48 | pass: false, 49 | message: () => 50 | `expected "${received}" to have been warned last.\n\nActual messages:\n\n - ${msgs}`, 51 | } 52 | } 53 | }, 54 | 55 | /** 56 | * 57 | * @param {string | RegExp} received 58 | * @param {number} n 59 | */ 60 | toHaveBeenWarnedTimes(received, n) { 61 | asserted.set(received.toString(), received) 62 | let found = 0 63 | warn.mock.calls.forEach(args => { 64 | const isFound = 65 | typeof received === 'string' 66 | ? args[0].indexOf(received) > -1 67 | : received.test(args[0]) 68 | if (isFound) { 69 | found++ 70 | } 71 | }) 72 | 73 | if (found === n) { 74 | return { 75 | pass: true, 76 | message: () => 77 | `expected "${received}" to have been warned ${n} times.`, 78 | } 79 | } else { 80 | return { 81 | pass: false, 82 | message: () => 83 | `expected "${received}" to have been warned ${n} times but got ${found}.`, 84 | } 85 | } 86 | }, 87 | }) 88 | 89 | /** @type {import('jest').SpyInstance} */ 90 | let warn 91 | /** @type {Map} */ 92 | const asserted = new Map() 93 | 94 | beforeEach(() => { 95 | asserted.clear() 96 | warn = jest.spyOn(console, 'warn') 97 | warn.mockImplementation(() => {}) 98 | }) 99 | 100 | afterEach(() => { 101 | const assertedArray = Array.from(asserted) 102 | const nonAssertedWarnings = warn.mock.calls 103 | .map(args => args[0]) 104 | .filter(received => { 105 | return !assertedArray.some(([key, assertedMsg]) => { 106 | return typeof assertedMsg === 'string' 107 | ? received.indexOf(assertedMsg) > -1 108 | : assertedMsg.test(received) 109 | }) 110 | }) 111 | warn.mockRestore() 112 | if (nonAssertedWarnings.length) { 113 | nonAssertedWarnings.forEach(warning => { 114 | console.warn(warning) 115 | }) 116 | throw new Error(`test case threw unexpected warnings.`) 117 | } 118 | }) 119 | } 120 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | "target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */, 5 | "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */, 6 | // "lib": [], /* Specify library files to be included in the compilation. */ 7 | "allowJs": true /* Allow javascript files to be compiled. */, 8 | "checkJs": true /* Report errors in .js files. */, 9 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 10 | "declaration": true /* Generates corresponding '.d.ts' file. */, 11 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 12 | // "outFile": "./", /* Concatenate and emit output to single file. */ 13 | // "outDir": "./", /* Redirect output structure to the directory. */ 14 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 15 | // "removeComments": true, /* Do not emit comments to output. */ 16 | // "noEmit": true, /* Do not emit outputs. */ 17 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 18 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 19 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 20 | 21 | /* Strict Type-Checking Options */ 22 | "strict": true /* Enable all strict type-checking options. */, 23 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 24 | // "strictNullChecks": true, /* Enable strict null checks. */ 25 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 26 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 27 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 28 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 29 | 30 | /* Additional Checks */ 31 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 32 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 33 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 34 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 35 | 36 | /* Module Resolution Options */ 37 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 38 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 39 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 40 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 41 | // "typeRoots": [], /* List of folders to include type definitions from. */ 42 | "types": [ 43 | "node" 44 | ] /* Type declaration files to be included in compilation. */, 45 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 46 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 47 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 48 | 49 | /* Source Map Options */ 50 | // "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 51 | // "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */ 52 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 53 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 54 | 55 | /* Experimental Options */ 56 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 57 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 58 | } 59 | } 60 | --------------------------------------------------------------------------------