All Projects โ†’ hustcc โ†’ Jest Canvas Mock

hustcc / Jest Canvas Mock

๐ŸŒ— A module used to mock canvas in Jest.

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Jest Canvas Mock

jest-how-do-i-mock-x
Runnable examples for common testing situations that often prove challenging
Stars: โœญ 63 (-66.67%)
Mutual labels:  mock, jest
Snapchat Clone
๐Ÿ‘ป A SnapChat clone built with React, Redux and Typescript. Styled with SASS. Tested with Cypress, Jest and Enzyme. Linted with Eslint and formatted with Prettier!
Stars: โœญ 770 (+307.41%)
Mutual labels:  jest, canvas
jest-launchdarkly-mock
Easily unit test LaunchDarkly feature flagged components with jest
Stars: โœญ 14 (-92.59%)
Mutual labels:  mock, jest
Jest Localstorage Mock
A module to mock window.localStorage and window.sessionStorage in Jest
Stars: โœญ 247 (+30.69%)
Mutual labels:  jest, mock
React Nativeish
React Native / React Native Web Boilerplate
Stars: โœญ 106 (-43.92%)
Mutual labels:  jest, mock
vue-admin-work
๐ŸŽ‰๐ŸŽ‰๐Ÿš€๐Ÿš€๐Ÿš€๐Ÿš€vue-admin-workๆ˜ฏไธ€ไธชไธญๅŽๅฐ็ณป็ปŸ็ฎก็†ๆ–นๆกˆใ€‚ไฝฟ็”จ vue2.x ๅŠๅ‘จ่พนๅ…จๅฎถๆกถๅทฅๅ…ทๅผ€ๅ‘่€Œๆฅใ€‚ๆ”ฏๆŒๅคš็งๅŠŸ่ƒฝ๏ผŒไธๅŒ่ง’่‰ฒๆƒ้™๐Ÿš€๐Ÿš€๐Ÿš€๐ŸŽ‰๐ŸŽ‰
Stars: โœญ 74 (-60.85%)
Mutual labels:  mock, echarts
Laravel Vue Boilerplate
๐Ÿ˜ A Laravel 6 SPA boilerplate with a users CRUD using Vue.js 2.6, GraphQL, Bootstrap 4, TypeScript, Sass, and Pug.
Stars: โœญ 472 (+149.74%)
Mutual labels:  ci, jest
Ol3echarts
๐ŸŒ ๐Ÿ“Š ol3Echarts | a openlayers extension to echarts
Stars: โœญ 229 (+21.16%)
Mutual labels:  echarts, canvas
Jest Action
Wraps and install Jest test runner in a github action.
Stars: โœญ 74 (-60.85%)
Mutual labels:  ci, jest
Deep Viz
A React component library, providing concise and beautiful diversity charts with Canvas, SVG, E-map, WebGL, Dom, based on data visualization experience and commercial data display practice.
Stars: โœญ 55 (-70.9%)
Mutual labels:  echarts, canvas
Vuex Mock Store
โœ…Simple and straightforward Vuex Store mock for vue-test-utils
Stars: โœญ 246 (+30.16%)
Mutual labels:  jest, mock
Mocky
Generate custom HTTP responses, the simpler way to test your Web Services
Stars: โœญ 1,762 (+832.28%)
Mutual labels:  ci, mock
Jest Mock Extended
Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
Stars: โœญ 224 (+18.52%)
Mutual labels:  jest, mock
split-tests
Split test files in Jest and Cypress into parallel CI jobs
Stars: โœญ 22 (-88.36%)
Mutual labels:  jest, ci
Sinon Jest Cheatsheet
Some examples on how to achieve the same goal with either of both libraries: sinon and jest. Also some of those goals achievable only by one of these tools.
Stars: โœญ 226 (+19.58%)
Mutual labels:  jest, mock
automock
A library for testing classes with auto mocking capabilities using jest-mock-extended
Stars: โœญ 26 (-86.24%)
Mutual labels:  mock, jest
Graphql Query Test Mock
Easily mock GraphQL queries in your Relay Modern / Apollo / any-other-GraphQL-client tests.
Stars: โœญ 49 (-74.07%)
Mutual labels:  jest, mock
Echarts
Apache ECharts is a powerful, interactive charting and data visualization library for browser
Stars: โœญ 49,119 (+25888.89%)
Mutual labels:  echarts, canvas
Javascript Testing Best Practices
๐Ÿ“—๐ŸŒ ๐Ÿšข Comprehensive and exhaustive JavaScript & Node.js testing best practices (August 2021)
Stars: โœญ 13,976 (+7294.71%)
Mutual labels:  ci, jest
Echarts Gl
Extension pack for Apache ECharts, providing globe visualization and 3D plots.
Stars: โœญ 2,227 (+1078.31%)
Mutual labels:  echarts

jest-canvas-mock

Mock canvas when run unit test cases with jest. For more browser environment, you can use jest-electron for real browser runtime.

Build Status Coverage Status npm npm Mentioned in Awesome Jest

Install

This should only be installed as a development dependency (devDependencies) as it is only designed for testing.

npm i --save-dev jest-canvas-mock

Setup

In your package.json under the jest, create a setupFiles array and add jest-canvas-mock to the array.

{
  "jest": {
    "setupFiles": ["jest-canvas-mock"]
  }
}

If you already have a setupFiles attribute you can also append jest-canvas-mock to the array.

{
  "jest": {
    "setupFiles": ["./__setups__/other.js", "jest-canvas-mock"]
  }
}

More about in configuration section.

Setup file

Alternatively you can create a new setup file which then requires this module or add the require statement to an existing setup file.

__setups__/canvas.js

import 'jest-canvas-mock';
// or
require('jest-canvas-mock');

Add that file to your setupFiles array:

"jest": {
  "setupFiles": [
    "./__setups__/canvas.js"
  ]
}

Mock Strategy

This mock strategy implements all the canvas functions and actually verifies the parameters. If a known condition would cause the browser to throw a TypeError or a DOMException, it emulates the error. For instance, the CanvasRenderingContext2D#arc function will throw a TypeError if the radius is negative, or if it was not provided with enough parameters.

// arc throws a TypeError when the argument length is less than 5
expect(() => ctx.arc(1, 2, 3, 4)).toThrow(TypeError);

// when radius is negative, arc throws a dom exception when all parameters are finite
expect(() => ctx.arc(0, 0, -10, 0, Math.PI * 2)).toThrow(DOMException);

The function will do Number type coercion and verify the inputs exactly like the browser does. So this is valid input.

expect(() => ctx.arc('10', '10', '20', '0', '6.14')).not.toThrow();

Another part of the strategy is to validate input types. When using the CanvasRenderingContext2D#fill function, if you pass it an invalid fillRule it will throw a TypeError just like the browser does.

expect(() => ctx.fill('invalid!')).toThrow(TypeError);
expect(() => ctx.fill(new Path2D(), 'invalid!')).toThrow(TypeError);

We try to follow the ECMAScript specification as closely as possible.

Snapshots

There are multiple ways to validate canvas state using snapshots. There are currently three methods attached to the CanvasRenderingContext2D class. The first way to use this feature is by using the __getEvents method.

/**
 * In order to see which functions and properties were used for the test, you can use `__getEvents`
 * to gather this information.
 */
const events = ctx.__getEvents();

expect(events).toMatchSnapshot(); // jest will assert the events match the snapshot

The second way is to inspect the current path associated with the context.

ctx.beginPath();
ctx.arc(1, 2, 3, 4, 5);
ctx.moveTo(6, 7);
ctx.rect(6, 7, 8, 9);
ctx.closePath();

/**
 * Any method that modifies the current path (and subpath) will be pushed to an event array. When
 * using the `__getPath` method, that array will sliced and usable for snapshots.
 */
const path = ctx.__getPath();
expect(path).toMatchSnapshot();

The third way is to inspect all of the successful draw calls submitted to the context.

ctx.drawImage(img, 0, 0);

/**
 * Every drawImage, fill, stroke, fillText, or strokeText function call will be logged in an event
 * array. This method will return those events here for inspection.
 */
const calls = ctx.__getDrawCalls();
expect(calls).toMatchSnapshot();

In some cases it may be useful to clear the events or draw calls that have already been logged.

// Clear events
ctx.__clearEvents();

// Clear draw calls
ctx.__clearDrawCalls();

Finally, it's possible to inspect the clipping region calls by using the __getClippingRegion function.

const clippingRegion = ctx.__getClippingRegion();
expect(clippingRegion).toMatchSnapshot();

The clipping region cannot be cleared because it's based on the stack values and when the .clip() function is called.

Override default mock return value

You can override the default mock return value in your test to suit your need. For example, to override return value of toDataURL:

canvas.toDataURL.mockReturnValueOnce(
  'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
);

Contributors

License

[email protected]hustcc.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].