{"id":13769681,"url":"https://github.com/hustcc/jest-canvas-mock","last_synced_at":"2025-05-14T02:05:49.435Z","repository":{"id":27870151,"uuid":"115256317","full_name":"hustcc/jest-canvas-mock","owner":"hustcc","description":":last_quarter_moon: A module used to mock canvas in Jest.","archived":false,"fork":false,"pushed_at":"2025-03-27T05:27:47.000Z","size":249,"stargazers_count":311,"open_issues_count":20,"forks_count":57,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-05-13T15:26:01.620Z","etag":null,"topics":["canvas","ci","echarts","jest","jest-test","mock"],"latest_commit_sha":null,"homepage":"https://github.com/hustcc/jest-canvas-mock","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hustcc.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":null,"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":["https://paypal.me/hustcc","https://atool.vip"]}},"created_at":"2017-12-24T10:40:47.000Z","updated_at":"2025-05-13T10:50:53.000Z","dependencies_parsed_at":"2024-01-12T10:26:58.649Z","dependency_job_id":"615543d0-bf89-46e2-8ec3-71bf09dd4383","html_url":"https://github.com/hustcc/jest-canvas-mock","commit_stats":{"total_commits":100,"total_committers":26,"mean_commits":"3.8461538461538463","dds":0.64,"last_synced_commit":"487799bca252f794795147201260cd720bcd5fe5"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hustcc%2Fjest-canvas-mock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hustcc%2Fjest-canvas-mock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hustcc%2Fjest-canvas-mock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hustcc%2Fjest-canvas-mock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hustcc","download_url":"https://codeload.github.com/hustcc/jest-canvas-mock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254052692,"owners_count":22006716,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["canvas","ci","echarts","jest","jest-test","mock"],"created_at":"2024-08-03T17:00:30.435Z","updated_at":"2025-05-14T02:05:44.424Z","avatar_url":"https://github.com/hustcc.png","language":"JavaScript","funding_links":["https://paypal.me/hustcc","https://atool.vip"],"categories":["Packages"],"sub_categories":["Mocks"],"readme":"# jest-canvas-mock\n\n\u003e Mock `canvas` when run unit test cases with jest. For more browser environment.\n\u003e - [jest-random-mock](https://github.com/hustcc/jest-random-mock) Mock `Math.random` in jest, with deterministic random generator.\n\u003e - [jest-date-mock](https://github.com/hustcc/jest-date-mock) Mock `Date` when run unit test with jest, test `Date` easily.\n\n[![Build Status](https://github.com/hustcc/jest-canvas-mock/workflows/build/badge.svg)](https://github.com/hustcc/jest-canvas-mock/actions/workflows/build.yml)\n[![Coverage Status](https://coveralls.io/repos/github/hustcc/jest-canvas-mock/badge.svg?branch=master)](https://coveralls.io/github/hustcc/jest-canvas-mock)\n[![npm](https://img.shields.io/npm/v/jest-canvas-mock.svg)](https://www.npmjs.com/package/jest-canvas-mock)\n[![npm](https://img.shields.io/npm/dm/jest-canvas-mock.svg)](https://www.npmjs.com/package/jest-canvas-mock)\n[![Mentioned in Awesome Jest](https://awesome.re/mentioned-badge.svg)](https://github.com/jest-community/awesome-jest)\n\n## Install\n\nThis should only be installed as a development dependency (`devDependencies`) as it is only designed for testing.\n\n```bash\nnpm i --save-dev jest-canvas-mock\n```\n\n## Setup\n\nIn your `package.json` under the `jest`, create a `setupFiles` array and add `jest-canvas-mock` to the array.\n\n```json\n{\n  \"jest\": {\n    \"setupFiles\": [\"jest-canvas-mock\"]\n  }\n}\n```\n\nIf you already have a `setupFiles` attribute you can also append `jest-canvas-mock` to the array.\n\n```json\n{\n  \"jest\": {\n    \"setupFiles\": [\"./__setups__/other.js\", \"jest-canvas-mock\"]\n  }\n}\n```\n\nMore about in [configuration section](https://facebook.github.io/jest/docs/en/configuration.html#content).\n\n## Setup file\n\nAlternatively you can create a new setup file which then requires this module or\nadd the `require` statement to an existing setup file.\n\n`__setups__/canvas.js`\n\n```js\nimport 'jest-canvas-mock';\n// or\nrequire('jest-canvas-mock');\n```\n\nAdd that file to your `setupFiles` array:\n\n```json\n\"jest\": {\n  \"setupFiles\": [\n    \"./__setups__/canvas.js\"\n  ]\n}\n```\n\n## Reset\n\nIf you reset the jest mocks (for example, with `jest.resetAllMocks()`), you can\ncall `setupJestCanvasMock()` to re-create it.\n\n```\nimport { setupJestCanvasMock } from 'jest-canvas-mock';\n\nbeforeEach(() =\u003e {\n  jest.resetAllMocks();\n  setupJestCanvasMock();\n});\n```\n\n## Mock Strategy\n\nThis mock strategy implements all the canvas functions and actually verifies the parameters. If a\nknown condition would cause the browser to throw a `TypeError` or a `DOMException`, it emulates the\nerror. For instance, the `CanvasRenderingContext2D#arc` function will throw a `TypeError` if the\nradius is negative, or if it was not provided with enough parameters.\n\n```ts\n// arc throws a TypeError when the argument length is less than 5\nexpect(() =\u003e ctx.arc(1, 2, 3, 4)).toThrow(TypeError);\n\n// when radius is negative, arc throws a dom exception when all parameters are finite\nexpect(() =\u003e ctx.arc(0, 0, -10, 0, Math.PI * 2)).toThrow(DOMException);\n```\n\nThe function will do `Number` type coercion and verify the inputs exactly like the browser does. So\nthis is valid input.\n\n```ts\nexpect(() =\u003e ctx.arc('10', '10', '20', '0', '6.14')).not.toThrow();\n```\n\nAnother part of the strategy is to validate input types. When using the\n`CanvasRenderingContext2D#fill` function, if you pass it an invalid `fillRule` it will throw a\n`TypeError` just like the browser does.\n\n```ts\nexpect(() =\u003e ctx.fill('invalid!')).toThrow(TypeError);\nexpect(() =\u003e ctx.fill(new Path2D(), 'invalid!')).toThrow(TypeError);\n```\n\nWe try to follow the ECMAScript specification as closely as possible.\n\n## Snapshots\n\nThere are multiple ways to validate canvas state using snapshots. There are currently three methods\nattached to the `CanvasRenderingContext2D` class. The first way to use this feature is by using the\n`__getEvents` method.\n\n```ts\n/**\n * In order to see which functions and properties were used for the test, you can use `__getEvents`\n * to gather this information.\n */\nconst events = ctx.__getEvents();\n\nexpect(events).toMatchSnapshot(); // jest will assert the events match the snapshot\n```\n\nThe second way is to inspect the current path associated with the context.\n\n```ts\nctx.beginPath();\nctx.arc(1, 2, 3, 4, 5);\nctx.moveTo(6, 7);\nctx.rect(6, 7, 8, 9);\nctx.closePath();\n\n/**\n * Any method that modifies the current path (and subpath) will be pushed to an event array. When\n * using the `__getPath` method, that array will sliced and usable for snapshots.\n */\nconst path = ctx.__getPath();\nexpect(path).toMatchSnapshot();\n```\n\nThe third way is to inspect all of the successful draw calls submitted to the context.\n\n```ts\nctx.drawImage(img, 0, 0);\n\n/**\n * Every drawImage, fill, stroke, fillText, or strokeText function call will be logged in an event\n * array. This method will return those events here for inspection.\n */\nconst calls = ctx.__getDrawCalls();\nexpect(calls).toMatchSnapshot();\n```\n\nIn some cases it may be useful to clear the events or draw calls that have already been logged.\n\n```ts\n// Clear events\nctx.__clearEvents();\n\n// Clear draw calls\nctx.__clearDrawCalls();\n```\n\nFinally, it's possible to inspect the clipping region calls by using the `__getClippingRegion`\nfunction.\n\n```ts\nconst clippingRegion = ctx.__getClippingRegion();\nexpect(clippingRegion).toMatchSnapshot();\n```\n\nThe clipping region cannot be cleared because it's based on the stack values and when the `.clip()`\nfunction is called.\n\n## Override default mock return value\n\nYou can override the default mock return value in your test to suit your need. For example, to override return value of `toDataURL`:\n\n```ts\ncanvas.toDataURL.mockReturnValueOnce(\n  'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='\n);\n```\n\n## Contributors\n\n- [@hustcc](https://github.com/hustcc)\n- [@jtenner](https://github.com/jtenner)\n- [@evanoc0](https://github.com/evanoc0)\n- [@lekha](https://github.com/lekha)\n- [@yonatankra](https://github.com/yonatankra)\n- [@LitoMore](https://github.com/LitoMore)\n- [@hrd543](https://github.com/hrd543)\n- [@danielrentz](https://github.com/danielrentz)\n- [@pedroordep](https://github.com/pedroordep)\n\n## License\n\nMIT@[hustcc](https://github.com/hustcc).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhustcc%2Fjest-canvas-mock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhustcc%2Fjest-canvas-mock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhustcc%2Fjest-canvas-mock/lists"}