Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
jest-canvas-mock
Advanced tools
The jest-canvas-mock npm package is a mock for the HTML Canvas API, designed to be used with the Jest testing framework. It allows developers to write tests for canvas operations without the need for a browser environment. This is particularly useful for unit testing canvas-related code in Node.js environments or in continuous integration systems where a DOM may not be available.
Mocking Canvas Context
This feature allows you to mock the 2D context of a canvas element, enabling you to test canvas drawing methods like fillRect.
import 'jest-canvas-mock';
test('mock canvas context', () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 100, 100);
expect(ctx.fillRect).toHaveBeenCalledWith(0, 0, 100, 100);
});
Mocking Canvas Image Data
This feature allows you to mock the creation of image data, which is useful for testing image manipulation on the canvas.
import 'jest-canvas-mock';
test('mock canvas image data', () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const imageData = ctx.createImageData(100, 100);
expect(imageData.data.length).toBe(40000);
});
Mocking Canvas Path Operations
This feature allows you to mock canvas path operations like beginPath, moveTo, lineTo, and stroke, which is useful for testing drawing paths on the canvas.
import 'jest-canvas-mock';
test('mock canvas path operations', () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(100, 100);
ctx.stroke();
expect(ctx.beginPath).toHaveBeenCalled();
expect(ctx.moveTo).toHaveBeenCalledWith(50, 50);
expect(ctx.lineTo).toHaveBeenCalledWith(100, 100);
expect(ctx.stroke).toHaveBeenCalled();
});
canvas-prebuilt is a prebuilt version of the 'canvas' package that provides a native canvas implementation for Node.js. It is similar to jest-canvas-mock in that it allows for canvas API testing, but it differs in that it provides an actual implementation rather than a mock, which may be more suitable for integration tests or when a real canvas environment is required.
Mock
canvas
when run unit test cases with jest. For more browser environment, you can use jest-electron for real browser runtime.
This should only be installed as a development dependency (devDependencies
) as it is only designed for testing.
npm i --save-dev jest-canvas-mock
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.
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"
]
}
If you reset the jest mocks (for example, with jest.resetAllMocks()
), you can
call setupJestCanvasMock()
to re-create it.
import { setupJestCanvasMock } from 'jest-canvas-mock';
beforeEach(() => {
jest.resetAllMocks();
setupJestCanvasMock();
});
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.
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.
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=='
);
MIT@hustcc.
FAQs
Mock a canvas in your jest tests.
The npm package jest-canvas-mock receives a total of 1,884,491 weekly downloads. As such, jest-canvas-mock popularity was classified as popular.
We found that jest-canvas-mock demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.