repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/fixtures/controller.polarArea/pointLabels/withTitle/right-centered-45.js | test/fixtures/controller.polarArea/pointLabels/withTitle/right-centered-45.js | module.exports = {
config: {
type: 'polarArea',
data: {
datasets: [{
data: [1, 2, 3, 4],
backgroundColor: ['#f003', '#0f03', '#00f3', '#0003']
}],
labels: [['label 1', 'line 2'], ['label 2', 'line 2'], ['label 3', 'line 2'], ['label 4', 'line 2']]
},
options: {
plugins: {
title: {
display: true,
position: 'right',
text: 'Chart Title'
},
legend: false
},
scales: {
r: {
startAngle: 45,
pointLabels: {
display: true,
centerPointLabels: true
}
}
}
}
},
options: {
spriteText: true
}
};
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/fixtures/controller.polarArea/pointLabels/withTitle/bottom-centered-45.js | test/fixtures/controller.polarArea/pointLabels/withTitle/bottom-centered-45.js | module.exports = {
config: {
type: 'polarArea',
data: {
datasets: [{
data: [1, 2, 3, 4],
backgroundColor: ['#f003', '#0f03', '#00f3', '#0003']
}],
labels: [['label 1', 'line 2'], ['label 2', 'line 2'], ['label 3', 'line 2'], ['label 4', 'line 2']]
},
options: {
plugins: {
title: {
display: true,
position: 'bottom',
text: 'Chart Title'
},
legend: false
},
scales: {
r: {
startAngle: 45,
pointLabels: {
display: true,
centerPointLabels: true
}
}
}
}
},
options: {
spriteText: true
}
};
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/types/autogen.js | test/types/autogen.js | import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import * as helpers from '../../dist/helpers.js';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
let fd;
try {
const fn = path.resolve(__dirname, 'autogen_helpers.ts');
fd = fs.openSync(fn, 'w+');
fs.writeSync(fd, 'import * as helpers from \'../../dist/helpers/index.js\';\n\n');
fs.writeSync(fd, 'const testKeys: unknown[] = [];\n');
for (const key of Object.keys(helpers)) {
if (key[0] !== '_' && typeof helpers[key] === 'function') {
fs.writeSync(fd, `testKeys.push(helpers.${key});\n`);
}
}
} finally {
if (fd !== undefined) {
fs.closeSync(fd);
}
}
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/plugin.colors.tests.js | test/specs/plugin.colors.tests.js | describe('Plugin.colors', () => {
describe('auto', jasmine.fixture.specs('plugin.colors'));
describe('Plugin.colors.chartDefaults', () => {
beforeAll(() => {
Chart.defaults.backgroundColor = ['green', 'yellow'];
});
afterAll(() => {
Chart.defaults.backgroundColor = 'rgba(0,0,0,0.1)';
});
it('should not use colors plugin when chart defaults are given', () => {
const chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 10],
label: 'dataset1'
}],
labels: ['label1', 'label2']
},
options: {
plugins: {
colors: {
enabled: true
}
}
}
});
const meta = chart.getDatasetMeta(0);
expect(meta.data[0].options.backgroundColor).toBe('green');
expect(meta.data[1].options.backgroundColor).toBe('yellow');
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.helpers.tests.js | test/specs/core.helpers.tests.js | describe('Core helper tests', function() {
var helpers;
beforeAll(function() {
helpers = window.Chart.helpers;
});
it('should generate integer ids', function() {
var uid = helpers.uid();
expect(uid).toEqual(jasmine.any(Number));
expect(helpers.uid()).toBe(uid + 1);
expect(helpers.uid()).toBe(uid + 2);
expect(helpers.uid()).toBe(uid + 3);
});
describe('clone', function() {
it('should not allow prototype pollution', function() {
const test = helpers.clone(JSON.parse('{"__proto__":{"polluted": true}}'));
expect(test.prototype).toBeUndefined();
expect(Object.prototype.polluted).toBeUndefined();
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.controller.tests.js | test/specs/core.controller.tests.js | describe('Chart', function() {
const overrides = Chart.overrides;
// https://github.com/chartjs/Chart.js/issues/2481
// See global.deprecations.tests.js for backward compatibility
it('should be defined and prototype of chart instances', function() {
var chart = acquireChart({});
expect(Chart).toBeDefined();
expect(Chart instanceof Object).toBeTruthy();
expect(chart.constructor).toBe(Chart);
expect(chart instanceof Chart).toBeTruthy();
});
it('should throw an error if the canvas is already in use', function() {
var config = {
type: 'line',
data: {
datasets: [{
data: [1, 2, 3, 4]
}],
labels: ['A', 'B', 'C', 'D']
}
};
var chart = acquireChart(config);
var canvas = chart.canvas;
function createChart() {
return new Chart(canvas, config);
}
expect(createChart).toThrow(new Error(
'Canvas is already in use. ' +
'Chart with ID \'' + chart.id + '\'' +
' must be destroyed before the canvas with ID \'' + chart.canvas.id + '\' can be reused.'
));
chart.destroy();
expect(createChart).not.toThrow();
});
describe('config initialization', function() {
it('should create missing config.data properties', function() {
var chart = acquireChart({});
var data = chart.data;
expect(data instanceof Object).toBeTruthy();
expect(data.labels instanceof Array).toBeTruthy();
expect(data.labels.length).toBe(0);
expect(data.datasets instanceof Array).toBeTruthy();
expect(data.datasets.length).toBe(0);
});
it('should not alter config.data references', function() {
var ds0 = {data: [10, 11, 12, 13]};
var ds1 = {data: [20, 21, 22, 23]};
var datasets = [ds0, ds1];
var labels = [0, 1, 2, 3];
var data = {labels: labels, datasets: datasets};
var chart = acquireChart({
type: 'line',
data: data
});
expect(chart.data).toBe(data);
expect(chart.data.labels).toBe(labels);
expect(chart.data.datasets).toBe(datasets);
expect(chart.data.datasets[0]).toBe(ds0);
expect(chart.data.datasets[1]).toBe(ds1);
expect(chart.data.datasets[0].data).toBe(ds0.data);
expect(chart.data.datasets[1].data).toBe(ds1.data);
});
it('should define chart.data as an alias for config.data', function() {
var config = {data: {labels: [], datasets: []}};
var chart = acquireChart(config);
expect(chart.data).toBe(config.data);
chart.data = {labels: [1, 2, 3], datasets: [{data: [4, 5, 6]}]};
expect(config.data).toBe(chart.data);
expect(config.data.labels).toEqual([1, 2, 3]);
expect(config.data.datasets[0].data).toEqual([4, 5, 6]);
config.data = {labels: [7, 8, 9], datasets: [{data: [10, 11, 12]}]};
expect(chart.data).toBe(config.data);
expect(chart.data.labels).toEqual([7, 8, 9]);
expect(chart.data.datasets[0].data).toEqual([10, 11, 12]);
});
it('should initialize config with default interaction options', function() {
var callback = function() {};
var defaults = Chart.defaults;
defaults.onHover = callback;
overrides.line.interaction = {
mode: 'test'
};
var chart = acquireChart({
type: 'line'
});
var options = chart.options;
expect(options.font.size).toBe(defaults.font.size);
expect(options.onHover).toBe(callback);
expect(options.hover.mode).toBe('test');
defaults.onHover = null;
delete overrides.line.interaction;
});
it('should initialize config with default hover options', function() {
var callback = function() {};
var defaults = Chart.defaults;
defaults.onHover = callback;
overrides.line.hover = {
mode: 'test'
};
var chart = acquireChart({
type: 'line'
});
var options = chart.options;
expect(options.font.size).toBe(defaults.font.size);
expect(options.onHover).toBe(callback);
expect(options.hover.mode).toBe('test');
defaults.onHover = null;
delete overrides.line.hover;
});
it('should override default options', function() {
var callback = function() {};
var defaults = Chart.defaults;
var defaultSpanGaps = defaults.datasets.line.spanGaps;
defaults.onHover = callback;
overrides.line.hover = {
mode: 'x-axis'
};
defaults.datasets.line.spanGaps = true;
var chart = acquireChart({
type: 'line',
options: {
spanGaps: false,
hover: {
mode: 'dataset',
},
plugins: {
title: {
position: 'bottom'
}
}
}
});
var options = chart.options;
expect(options.spanGaps).toBe(false);
expect(options.hover.mode).toBe('dataset');
expect(options.plugins.title.position).toBe('bottom');
defaults.onHover = null;
delete overrides.line.hover;
defaults.datasets.line.spanGaps = defaultSpanGaps;
});
it('should initialize config with default dataset options', function() {
var defaults = Chart.defaults.datasets.pie;
var chart = acquireChart({
type: 'pie'
});
var options = chart.options;
expect(options.circumference).toBe(defaults.circumference);
});
it('should override axis positions that are incorrect', function() {
var chart = acquireChart({
type: 'line',
options: {
scales: {
x: {
position: 'left',
},
y: {
position: 'bottom'
}
}
}
});
var scaleOptions = chart.options.scales;
expect(scaleOptions.x.position).toBe('bottom');
expect(scaleOptions.y.position).toBe('left');
});
it('should throw an error if the chart type is incorrect', function() {
function createChart() {
acquireChart({
type: 'area',
data: {
datasets: [{
label: 'first',
data: [10, 20]
}],
labels: ['0', '1'],
},
options: {
scales: {
x: {
type: 'linear',
position: 'left',
},
y: {
type: 'category',
position: 'bottom'
}
}
}
});
}
expect(createChart).toThrow(new Error('"area" is not a registered controller.'));
});
it('should initialize the data object', function() {
const chart = acquireChart({type: 'bar'});
expect(chart.data).toEqual(jasmine.objectContaining({labels: [], datasets: []}));
chart.data = {};
expect(chart.data).toEqual(jasmine.objectContaining({labels: [], datasets: []}));
chart.data = null;
expect(chart.data).toEqual(jasmine.objectContaining({labels: [], datasets: []}));
chart.data = undefined;
expect(chart.data).toEqual(jasmine.objectContaining({labels: [], datasets: []}));
});
describe('should disable hover', function() {
it('when options.hover=false', function() {
var chart = acquireChart({
type: 'line',
options: {
hover: false
}
});
expect(chart.options.hover).toBeFalse();
});
it('when options.interaction=false and options.hover is not defined', function() {
var chart = acquireChart({
type: 'line',
options: {
interaction: false
}
});
expect(chart.options.hover).toBeFalse();
});
it('when options.interaction=false and options.hover is defined', function() {
var chart = acquireChart({
type: 'line',
options: {
interaction: false,
hover: {mode: 'nearest'}
}
});
expect(chart.options.hover).toBeFalse();
});
});
it('should activate element on hover', async function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
}
});
var point = chart.getDatasetMeta(0).data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(chart.getActiveElements()).toEqual([{datasetIndex: 0, index: 1, element: point}]);
});
it('should handle changing the events at runtime', async function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
events: ['click']
}
});
var point1 = chart.getDatasetMeta(0).data[1];
var point2 = chart.getDatasetMeta(0).data[2];
await jasmine.triggerMouseEvent(chart, 'click', point1);
expect(chart.getActiveElements()).toEqual([{datasetIndex: 0, index: 1, element: point1}]);
chart.options.events = ['mousemove'];
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point2);
expect(chart.getActiveElements()).toEqual([{datasetIndex: 0, index: 2, element: point2}]);
});
it('should activate element on hover when minPadding pixels outside chart area', async function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100],
hoverRadius: 0
}],
},
options: {
scales: {
x: {display: false},
y: {display: false}
}
}
});
var point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', {x: 1, y: point.y});
expect(chart.getActiveElements()).toEqual([{datasetIndex: 0, index: 0, element: point}]);
});
it('should not activate elements when hover is disabled', async function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
hover: false
}
});
var point = chart.getDatasetMeta(0).data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(chart.getActiveElements()).toEqual([]);
});
it('should not change the active elements when outside chartArea, except for mouseout', async function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100],
hoverRadius: 0
}],
},
options: {
scales: {
x: {display: false},
y: {display: false}
},
layout: {
padding: 5
}
}
});
var point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: point.y});
expect(chart.getActiveElements()).toEqual([{datasetIndex: 0, index: 0, element: point}]);
await jasmine.triggerMouseEvent(chart, 'mousemove', {x: 1, y: 1});
expect(chart.getActiveElements()).toEqual([{datasetIndex: 0, index: 0, element: point}]);
await jasmine.triggerMouseEvent(chart, 'mouseout', {x: 1, y: 1});
expect(chart.tooltip.getActiveElements()).toEqual([]);
});
});
describe('when merging scale options', function() {
beforeEach(function() {
Chart.helpers.merge(Chart.defaults.scale, {
_jasmineCheckA: 'a0',
_jasmineCheckB: 'b0',
_jasmineCheckC: 'c0'
});
Chart.helpers.merge(Chart.defaults.scales.logarithmic, {
_jasmineCheckB: 'b1',
_jasmineCheckC: 'c1',
});
});
afterEach(function() {
delete Chart.defaults.scale._jasmineCheckA;
delete Chart.defaults.scale._jasmineCheckB;
delete Chart.defaults.scale._jasmineCheckC;
delete Chart.defaults.scales.logarithmic._jasmineCheckB;
delete Chart.defaults.scales.logarithmic._jasmineCheckC;
});
it('should default to "category" for x scales and "linear" for y scales', function() {
var chart = acquireChart({
type: 'line',
options: {
scales: {
xFoo0: {},
xFoo1: {},
yBar0: {},
yBar1: {},
}
}
});
expect(chart.scales.xFoo0.type).toBe('category');
expect(chart.scales.xFoo1.type).toBe('category');
expect(chart.scales.yBar0.type).toBe('linear');
expect(chart.scales.yBar1.type).toBe('linear');
});
it('should correctly apply defaults on central scale', function() {
var chart = acquireChart({
type: 'line',
options: {
scales: {
foo: {
axis: 'x',
type: 'logarithmic',
_jasmineCheckC: 'c2',
_jasmineCheckD: 'd2'
}
}
}
});
// let's check a few values from the user options and defaults
expect(chart.scales.foo.type).toBe('logarithmic');
expect(chart.scales.foo.options).toEqual(chart.options.scales.foo);
expect(chart.scales.foo.options).toEqual(
jasmine.objectContaining({
_jasmineCheckA: 'a0',
_jasmineCheckB: 'b1',
_jasmineCheckC: 'c2',
_jasmineCheckD: 'd2'
}));
});
it('should correctly apply defaults on xy scales', function() {
var chart = acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'logarithmic',
_jasmineCheckC: 'c2',
_jasmineCheckD: 'd2'
},
y: {
type: 'time',
_jasmineCheckC: 'c2',
_jasmineCheckE: 'e2'
}
}
}
});
expect(chart.scales.x.type).toBe('logarithmic');
expect(chart.scales.x.options).toEqual(chart.options.scales.x);
expect(chart.scales.x.options).toEqual(
jasmine.objectContaining({
_jasmineCheckA: 'a0',
_jasmineCheckB: 'b1',
_jasmineCheckC: 'c2',
_jasmineCheckD: 'd2'
}));
expect(chart.scales.y.type).toBe('time');
expect(chart.scales.y.options).toEqual(chart.options.scales.y);
expect(chart.scales.y.options).toEqual(
jasmine.objectContaining({
_jasmineCheckA: 'a0',
_jasmineCheckB: 'b0',
_jasmineCheckC: 'c2',
_jasmineCheckE: 'e2'
}));
});
it('should not alter defaults when merging config', function() {
var chart = acquireChart({
type: 'line',
options: {
_jasmineCheck: 42,
scales: {
x: {
type: 'linear',
_jasmineCheck: 42,
},
y: {
type: 'category',
_jasmineCheck: 42,
}
}
}
});
expect(chart.options._jasmineCheck).toBeDefined();
expect(chart.scales.x.options._jasmineCheck).toBeDefined();
expect(chart.scales.y.options._jasmineCheck).toBeDefined();
expect(Chart.overrides.line._jasmineCheck).not.toBeDefined();
expect(Chart.defaults._jasmineCheck).not.toBeDefined();
expect(Chart.defaults.scales.linear._jasmineCheck).not.toBeDefined();
expect(Chart.defaults.scales.category._jasmineCheck).not.toBeDefined();
});
it('should ignore proxy passed as scale options', function() {
let failure = false;
const chart = acquireChart({
type: 'line',
data: [],
options: {
scales: {
x: {
grid: {
color: ctx => {
if (!ctx.tick) {
failure = true;
}
}
}
}
}
}
});
chart.options.scales = {
x: chart.options.scales.x,
y: {
type: 'linear',
position: 'right'
}
};
chart.update();
expect(failure).toEqual(false);
});
it('should ignore array passed as scale options', function() {
const chart = acquireChart({
type: 'line',
data: [],
options: {
scales: {
xAxes: [{id: 'xAxes', type: 'category'}]
}
}
});
expect(chart.scales.xAxes).not.toBeDefined();
});
});
describe('Updating options', function() {
it('update should result to same set of options as construct', function() {
var chart = acquireChart({
type: 'line',
data: [],
options: {
animation: false,
locale: 'en-US',
responsive: false
}
});
const options = chart.options;
chart.options = {
animation: false,
locale: 'en-US',
responsive: false
};
chart.update();
expect(chart.options).toEqualOptions(options);
});
});
describe('config.options.responsive: true (maintainAspectRatio: false)', function() {
it('should fill parent width and height', function() {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: 'width: 150px; height: 245px'
},
wrapper: {
style: 'width: 300px; height: 350px'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
});
it('should call onResize with correct arguments and context', function() {
let count = 0;
let correctThis = false;
let size = {
width: 0,
height: 0
};
acquireChart({
options: {
responsive: true,
maintainAspectRatio: false,
onResize(chart, newSize) {
count++;
correctThis = this === chart;
size.width = newSize.width;
size.height = newSize.height;
}
}
}, {
canvas: {
style: 'width: 150px; height: 245px'
},
wrapper: {
style: 'width: 300px; height: 350px'
}
});
expect(count).toEqual(1);
expect(correctThis).toBeTrue();
expect(size).toEqual({width: 300, height: 350});
});
it('should resize the canvas when parent width changes', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 300px; height: 350px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
var wrapper = chart.canvas.parentNode;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 350,
rw: 455, rh: 350,
});
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 150, dh: 350,
rw: 150, rh: 350,
});
done();
});
wrapper.style.width = '150px';
});
wrapper.style.width = '455px';
});
it('should restore the original size when parent became invisible', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 300px; height: 350px; position: relative'
}
});
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
var original = chart.resize;
chart.resize = function() {
fail('resize should not have been called');
};
var wrapper = chart.canvas.parentNode;
wrapper.style.display = 'none';
setTimeout(function() {
expect(wrapper.clientWidth).toEqual(0);
expect(wrapper.clientHeight).toEqual(0);
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
chart.resize = original;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
done();
});
wrapper.style.display = 'block';
}, 200);
});
});
it('should resize the canvas when parent is RTL and width changes', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 300px; height: 350px; position: relative; direction: rtl'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
var wrapper = chart.canvas.parentNode;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 350,
rw: 455, rh: 350,
});
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 150, dh: 350,
rw: 150, rh: 350,
});
done();
});
wrapper.style.width = '150px';
});
wrapper.style.width = '455px';
});
it('should resize the canvas when parent height changes', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 300px; height: 350px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 350,
rw: 300, rh: 350,
});
var wrapper = chart.canvas.parentNode;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 300, dh: 455,
rw: 300, rh: 455,
});
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 300, dh: 150,
rw: 300, rh: 150,
});
done();
});
wrapper.style.height = '150px';
});
wrapper.style.height = '455px';
});
it('should not include parent padding when resizing the canvas', function(done) {
var chart = acquireChart({
type: 'line',
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'padding: 50px; width: 320px; height: 350px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 320, dh: 350,
rw: 320, rh: 350,
});
var wrapper = chart.canvas.parentNode;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 355,
rw: 455, rh: 355,
});
done();
});
wrapper.style.height = '355px';
wrapper.style.width = '455px';
});
it('should resize the canvas when the canvas display style changes from "none" to "block"', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: 'display: none;'
},
wrapper: {
style: 'width: 320px; height: 350px'
}
});
var canvas = chart.canvas;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 320, dh: 350,
rw: 320, rh: 350,
});
done();
});
canvas.style.display = 'block';
});
it('should resize the canvas when the wrapper display style changes from "none" to "block"', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'display: none; width: 460px; height: 380px'
}
});
var wrapper = chart.canvas.parentNode;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 460, dh: 380,
rw: 460, rh: 380,
});
done();
});
wrapper.style.display = 'block';
});
it('should resize the canvas when the wrapper has display style changes from "none" to "block"', function(done) {
// https://github.com/chartjs/Chart.js/issues/4659
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'display: none; max-width: 600px; max-height: 400px;'
}
});
var wrapper = chart.canvas.parentNode;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 600, dh: 300,
rw: 600, rh: 300,
});
done();
});
wrapper.style.display = 'block';
});
// https://github.com/chartjs/Chart.js/issues/5485
it('should resize the canvas when the devicePixelRatio changes', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false,
devicePixelRatio: 1
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 400px; height: 200px; position: relative'
}
});
expect(chart).toBeChartOfSize({
dw: 400, dh: 200,
rw: 400, rh: 200,
});
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 400, dh: 200,
rw: 800, rh: 400,
});
done();
});
chart.options.devicePixelRatio = 2;
chart.resize();
});
// https://github.com/chartjs/Chart.js/issues/3790
it('should resize the canvas if attached to the DOM after construction', function(done) {
var canvas = document.createElement('canvas');
var wrapper = document.createElement('div');
var body = window.document.body;
var chart = new Chart(canvas, {
type: 'line',
options: {
responsive: true,
maintainAspectRatio: false
}
});
expect(chart).toBeChartOfSize({
dw: 0, dh: 0,
rw: 0, rh: 0,
});
expect(chart.chartArea).toBeUndefined();
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 355,
rw: 455, rh: 355,
});
expect(chart.chartArea).not.toBeUndefined();
body.removeChild(wrapper);
chart.destroy();
done();
});
wrapper.style.cssText = 'width: 455px; height: 355px';
wrapper.appendChild(canvas);
body.appendChild(wrapper);
});
it('should resize the canvas when attached to a different parent', function(done) {
var canvas = document.createElement('canvas');
var wrapper = document.createElement('div');
var body = window.document.body;
var chart = new Chart(canvas, {
type: 'line',
options: {
responsive: true,
maintainAspectRatio: false
}
});
expect(chart).toBeChartOfSize({
dw: 0, dh: 0,
rw: 0, rh: 0,
});
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 355,
rw: 455, rh: 355,
});
var target = document.createElement('div');
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 640, dh: 480,
rw: 640, rh: 480,
});
body.removeChild(wrapper);
body.removeChild(target);
chart.destroy();
done();
});
target.style.cssText = 'width: 640px; height: 480px';
target.appendChild(canvas);
body.appendChild(target);
});
wrapper.style.cssText = 'width: 455px; height: 355px';
wrapper.appendChild(canvas);
body.appendChild(wrapper);
});
// https://github.com/chartjs/Chart.js/issues/3521
it('should resize the canvas after the wrapper has been re-attached to the DOM', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 320px; height: 350px'
}
});
expect(chart).toBeChartOfSize({
dw: 320, dh: 350,
rw: 320, rh: 350,
});
var wrapper = chart.canvas.parentNode;
var parent = wrapper.parentNode;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 320, dh: 355,
rw: 320, rh: 355,
});
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 455, dh: 355,
rw: 455, rh: 355,
});
done();
});
parent.removeChild(wrapper);
wrapper.style.width = '455px';
parent.appendChild(wrapper);
});
parent.removeChild(wrapper);
setTimeout(() => {
parent.appendChild(wrapper);
wrapper.style.height = '355px';
}, 0);
});
// https://github.com/chartjs/Chart.js/issues/9875
it('should detect detach/attach in series', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 320px; height: 350px'
}
});
var wrapper = chart.canvas.parentNode;
var parent = wrapper.parentNode;
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 320, dh: 350,
rw: 320, rh: 350,
});
done();
});
parent.removeChild(wrapper);
parent.appendChild(wrapper);
});
it('should detect detach/attach/detach in series', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 320px; height: 350px'
}
});
var wrapper = chart.canvas.parentNode;
var parent = wrapper.parentNode;
waitForResize(chart, function() {
fail();
});
parent.removeChild(wrapper);
parent.appendChild(wrapper);
parent.removeChild(wrapper);
setTimeout(function() {
expect(chart.attached).toBeFalse();
done();
}, 100);
});
it('should detect attach/detach in series', function(done) {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: false
}
}, {
canvas: {
style: ''
},
wrapper: {
style: 'width: 320px; height: 350px'
}
});
var wrapper = chart.canvas.parentNode;
var parent = wrapper.parentNode;
parent.removeChild(wrapper);
setTimeout(function() {
expect(chart.attached).toBeFalse();
waitForResize(chart, function() {
fail();
});
parent.appendChild(wrapper);
parent.removeChild(wrapper);
setTimeout(function() {
expect(chart.attached).toBeFalse();
done();
}, 100);
}, 100);
});
// https://github.com/chartjs/Chart.js/issues/4737
it('should resize the canvas when re-creating the chart', function(done) {
var chart = acquireChart({
options: {
responsive: true
}
}, {
wrapper: {
style: 'width: 320px'
}
});
var wrapper = chart.canvas.parentNode;
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | true |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/plugin.subtitle.tests.js | test/specs/plugin.subtitle.tests.js | describe('plugin.subtitle', function() {
describe('auto', jasmine.fixture.specs('plugin.subtitle'));
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/controller.radar.tests.js | test/specs/controller.radar.tests.js | describe('Chart.controllers.radar', function() {
describe('auto', jasmine.fixture.specs('controller.radar'));
it('should be registered as dataset controller', function() {
expect(typeof Chart.controllers.radar).toBe('function');
});
it('Should be constructed', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: []
}],
labels: []
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.type).toBe('radar');
expect(meta.controller).not.toBe(undefined);
expect(meta.controller.index).toBe(0);
expect(meta.data).toEqual([]);
meta.controller.updateIndex(1);
expect(meta.controller.index).toBe(1);
});
it('Should create arc elements for each data item during initialization', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 15, 0, 4]
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.dataset instanceof Chart.elements.LineElement).toBe(true); // line element
expect(meta.data.length).toBe(4); // 4 points created
expect(meta.data[0] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.PointElement).toBe(true);
});
it('should draw all elements', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 15, 0, 4]
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
spyOn(meta.dataset, 'draw');
spyOn(meta.data[0], 'draw');
spyOn(meta.data[1], 'draw');
spyOn(meta.data[2], 'draw');
spyOn(meta.data[3], 'draw');
chart.update();
expect(meta.dataset.draw.calls.count()).toBe(1);
expect(meta.data[0].draw.calls.count()).toBe(1);
expect(meta.data[1].draw.calls.count()).toBe(1);
expect(meta.data[2].draw.calls.count()).toBe(1);
expect(meta.data[3].draw.calls.count()).toBe(1);
});
it('should draw all elements with object notation and default key', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [{r: 10}, {r: 20}, {r: 15}]
}],
labels: ['label1', 'label2', 'label3']
}
});
var meta = chart.getDatasetMeta(0);
spyOn(meta.dataset, 'draw');
spyOn(meta.data[0], 'draw');
spyOn(meta.data[1], 'draw');
spyOn(meta.data[2], 'draw');
chart.update();
expect(meta.dataset.draw.calls.count()).toBe(1);
expect(meta.data[0].draw.calls.count()).toBe(1);
expect(meta.data[1].draw.calls.count()).toBe(1);
expect(meta.data[2].draw.calls.count()).toBe(1);
});
it('should update elements', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 15, 0, 4]
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
showLine: true,
plugins: {
legend: false,
title: false,
},
elements: {
line: {
backgroundColor: 'rgb(255, 0, 0)',
borderCapStyle: 'round',
borderColor: 'rgb(0, 255, 0)',
borderDash: [],
borderDashOffset: 0.1,
borderJoinStyle: 'bevel',
borderWidth: 1.2,
fill: true,
tension: 0.1,
},
point: {
backgroundColor: Chart.defaults.backgroundColor,
borderWidth: 1,
borderColor: Chart.defaults.borderColor,
hitRadius: 1,
hoverRadius: 4,
hoverBorderWidth: 1,
radius: 3,
pointStyle: 'circle'
}
}
}
});
var meta = chart.getDatasetMeta(0);
chart.reset(); // reset first
// Line element
expect(meta.dataset.options).toEqual(jasmine.objectContaining({
backgroundColor: 'rgb(255, 0, 0)',
borderCapStyle: 'round',
borderColor: 'rgb(0, 255, 0)',
borderDash: [],
borderDashOffset: 0.1,
borderJoinStyle: 'bevel',
borderWidth: 1.2,
fill: true,
tension: 0.1,
}));
[
{x: 256, y: 256},
{x: 256, y: 256},
{x: 256, y: 256},
{x: 256, y: 256},
].forEach(function(expected, i) {
expect(meta.data[i].x).withContext(i).toBeCloseToPixel(expected.x);
expect(meta.data[i].y).withContext(i).toBeCloseToPixel(expected.y);
expect(meta.data[i].options).withContext(i).toEqual(jasmine.objectContaining({
backgroundColor: Chart.defaults.backgroundColor,
borderWidth: 1,
borderColor: Chart.defaults.borderColor,
hitRadius: 1,
radius: 3,
pointStyle: 'circle',
}));
});
chart.update();
[
{x: 256, y: 122, cppx: 246, cppy: 122, cpnx: 272, cpny: 122},
{x: 457, y: 256, cppx: 457, cppy: 249, cpnx: 457, cpny: 262},
{x: 256, y: 256, cppx: 277, cppy: 256, cpnx: 250, cpny: 256},
{x: 202, y: 256, cppx: 202, cppy: 260, cpnx: 202, cpny: 246},
].forEach(function(expected, i) {
expect(meta.data[i].x).withContext(i).toBeCloseToPixel(expected.x);
expect(meta.data[i].y).withContext(i).toBeCloseToPixel(expected.y);
expect(meta.data[i].cp1x).withContext(i).toBeCloseToPixel(expected.cppx);
expect(meta.data[i].cp1y).withContext(i).toBeCloseToPixel(expected.cppy);
expect(meta.data[i].cp2x).withContext(i).toBeCloseToPixel(expected.cpnx);
expect(meta.data[i].cp2y).withContext(i).toBeCloseToPixel(expected.cpny);
expect(meta.data[i].options).withContext(i).toEqual(jasmine.objectContaining({
backgroundColor: Chart.defaults.backgroundColor,
borderWidth: 1,
borderColor: Chart.defaults.borderColor,
hitRadius: 1,
radius: 3,
pointStyle: 'circle',
}));
});
// Use dataset level styles for lines & points
chart.data.datasets[0].tension = 0;
chart.data.datasets[0].backgroundColor = 'rgb(98, 98, 98)';
chart.data.datasets[0].borderColor = 'rgb(8, 8, 8)';
chart.data.datasets[0].borderWidth = 0.55;
chart.data.datasets[0].borderCapStyle = 'butt';
chart.data.datasets[0].borderDash = [2, 3];
chart.data.datasets[0].borderDashOffset = 7;
chart.data.datasets[0].borderJoinStyle = 'miter';
chart.data.datasets[0].fill = false;
// point styles
chart.data.datasets[0].pointRadius = 22;
chart.data.datasets[0].hitRadius = 3.3;
chart.data.datasets[0].pointBackgroundColor = 'rgb(128, 129, 130)';
chart.data.datasets[0].pointBorderColor = 'rgb(56, 57, 58)';
chart.data.datasets[0].pointBorderWidth = 1.123;
chart.update();
expect(meta.dataset.options).toEqual(jasmine.objectContaining({
backgroundColor: 'rgb(98, 98, 98)',
borderCapStyle: 'butt',
borderColor: 'rgb(8, 8, 8)',
borderDash: [2, 3],
borderDashOffset: 7,
borderJoinStyle: 'miter',
borderWidth: 0.55,
fill: false,
tension: 0,
}));
// Since tension is now 0, we don't care about the control points
[
{x: 256, y: 122},
{x: 457, y: 256},
{x: 256, y: 256},
{x: 202, y: 256},
].forEach(function(expected, i) {
expect(meta.data[i].x).withContext(i).toBeCloseToPixel(expected.x);
expect(meta.data[i].y).withContext(i).toBeCloseToPixel(expected.y);
expect(meta.data[i].options).withContext(i).toEqual(jasmine.objectContaining({
backgroundColor: 'rgb(128, 129, 130)',
borderWidth: 1.123,
borderColor: 'rgb(56, 57, 58)',
hitRadius: 3.3,
radius: 22,
pointStyle: 'circle'
}));
});
});
describe('Interactions', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'radar',
data: {
labels: ['label1', 'label2', 'label3', 'label4'],
datasets: [{
data: [10, 15, 0, 4]
}]
},
options: {
elements: {
point: {
backgroundColor: 'rgb(100, 150, 200)',
borderColor: 'rgb(50, 100, 150)',
borderWidth: 2,
radius: 3
}
}
}
});
});
it('should handle default hover styles', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('#3187DD');
expect(point.options.borderColor).toBe('#175A9D');
expect(point.options.borderWidth).toBe(1);
expect(point.options.radius).toBe(4);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(3);
});
it('should handle hover styles defined via dataset properties', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.data.datasets[0], {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
hoverRadius: 4.2
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
expect(point.options.borderWidth).toBe(8.4);
expect(point.options.radius).toBe(4.2);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(3);
});
it('should handle hover styles defined via element options', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.options.elements.point, {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
hoverRadius: 4.2
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
expect(point.options.borderWidth).toBe(8.4);
expect(point.options.radius).toBe(4.2);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(3);
});
});
it('should allow pointBorderWidth to be set to 0', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 15, 0, 4],
pointBorderWidth: 0
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
var point = meta.data[0];
expect(point.options.borderWidth).toBe(0);
});
it('should use the pointRadius setting over the radius setting', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 15, 0, 4],
pointRadius: 10,
radius: 15,
}, {
data: [20, 20, 20, 20],
radius: 20
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
expect(meta0.data[0].options.radius).toBe(10);
expect(meta1.data[0].options.radius).toBe(20);
});
it('should return id for value scale', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 15, 0, 4],
pointBorderWidth: 0
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
test: {
axis: 'r'
}
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.vScale.id).toBe('test');
});
it('should not override tooltip title and label callbacks', async() => {
const chart = window.acquireChart({
type: 'radar',
data: {
labels: ['Label 1', 'Label 2'],
datasets: [{
data: [21, 79],
label: 'Dataset 1'
}, {
data: [33, 67],
label: 'Dataset 2'
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
}
});
const {tooltip} = chart;
const point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Label 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Dataset 1: 21'],
after: []
}]);
chart.options.plugins.tooltip = {mode: 'dataset'};
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Dataset 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Label 1: 21'],
after: []
}, {
before: [],
lines: ['Label 2: 79'],
after: []
}]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/scale.linear.tests.js | test/specs/scale.linear.tests.js | function getLabels(scale) {
return scale.ticks.map(t => t.label);
}
describe('Linear Scale', function() {
describe('auto', jasmine.fixture.specs('scale.linear'));
it('Should register the constructor with the registry', function() {
var Constructor = Chart.registry.getScale('linear');
expect(Constructor).not.toBe(undefined);
expect(typeof Constructor).toBe('function');
});
it('Should have the correct default config', function() {
var defaultConfig = Chart.defaults.scales.linear;
expect(defaultConfig.ticks.callback).toEqual(jasmine.any(Function));
});
it('Should correctly determine the max & min data values', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 0, -5, 78, -100]
}, {
yAxisID: 'y2',
data: [-1000, 1000],
}, {
yAxisID: 'y',
data: [150]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear'
},
y2: {
type: 'linear',
position: 'right',
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(-100);
expect(chart.scales.y.max).toBe(150);
});
it('Should handle when only a min value is provided', () => {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
yAxisID: 'y',
data: [200]
}],
},
options: {
scales: {
y: {
type: 'linear',
min: 250
}
}
}
});
expect(chart.scales.y.min).toBe(250);
});
it('Should handle when only a max value is provided', () => {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
yAxisID: 'y',
data: [200]
}],
},
options: {
scales: {
y: {
type: 'linear',
max: 150
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.max).toBe(150);
});
it('Should correctly determine the max & min of string data values', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: ['10', '5', '0', '-5', '78', '-100']
}, {
yAxisID: 'y2',
data: ['-1000', '1000'],
}, {
yAxisID: 'y',
data: ['150']
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear'
},
y2: {
type: 'linear',
position: 'right'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(-100);
expect(chart.scales.y.max).toBe(150);
});
it('Should correctly determine the max & min when no values provided and suggested minimum and maximum are set', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: []
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
suggestedMin: -10,
suggestedMax: 15
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(-10);
expect(chart.scales.y.max).toBe(15);
});
it('Should correctly determine the max & min when no datasets are associated and suggested minimum and maximum are set', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: []
},
options: {
scales: {
y: {
type: 'linear',
suggestedMin: -10,
suggestedMax: 0
}
}
}
});
expect(chart.scales.y.min).toBe(-10);
expect(chart.scales.y.max).toBe(0);
});
it('Should correctly determine the max & min data values ignoring hidden datasets', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: ['10', '5', '0', '-5', '78', '-100']
}, {
yAxisID: 'y2',
data: ['-1000', '1000'],
}, {
yAxisID: 'y',
data: ['150'],
hidden: true
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear'
},
y2: {
position: 'right',
type: 'linear'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(-100);
expect(chart.scales.y.max).toBe(80);
});
it('Should correctly determine the max & min data values ignoring data that is NaN', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [null, 90, NaN, undefined, 45, 30, Infinity, -Infinity]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
},
options: {
scales: {
y: {
type: 'linear',
beginAtZero: false
}
}
}
});
expect(chart.scales.y.min).toBe(30);
expect(chart.scales.y.max).toBe(90);
// Scale is now stacked
chart.scales.y.options.stacked = true;
chart.update();
expect(chart.scales.y.min).toBe(30);
expect(chart.scales.y.max).toBe(90);
chart.scales.y.options.beginAtZero = true;
chart.update();
expect(chart.scales.y.min).toBe(0);
expect(chart.scales.y.max).toBe(90);
});
it('Should correctly determine the max & min data values for small numbers', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [-1e-8, 3e-8, -4e-8, 6e-8]
}],
labels: ['a', 'b', 'c', 'd']
},
options: {
scales: {
y: {
type: 'linear'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min * 1e8).toBeCloseTo(-4);
expect(chart.scales.y.max * 1e8).toBeCloseTo(6);
});
it('Should correctly determine the max & min for scatter data', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [{
x: 10,
y: 100
}, {
x: -10,
y: 0
}, {
x: 0,
y: 0
}, {
x: 99,
y: 7
}]
}],
},
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
chart.update();
expect(chart.scales.x.min).toBe(-20);
expect(chart.scales.x.max).toBe(100);
expect(chart.scales.y.min).toBe(0);
expect(chart.scales.y.max).toBe(100);
});
it('Should correctly get the label for the given index', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [{
x: 10,
y: 100
}, {
x: -10,
y: 0
}, {
x: 0,
y: 0
}, {
x: 99,
y: 7
}]
}],
},
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
chart.update();
expect(chart.scales.y.getLabelForValue(7)).toBe('7');
});
it('Should correctly use the locale setting when getting a label', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [{
x: 10,
y: 100
}, {
x: -10,
y: 0
}, {
x: 0,
y: 0
}, {
x: 99,
y: 7
}]
}],
},
options: {
locale: 'de-DE',
scales: {
x: {
type: 'linear',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
chart.update();
expect(chart.scales.y.getLabelForValue(7.07)).toBe('7,07');
});
it('Should correctly determine the min and max data values when stacked mode is turned on', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 0, -5, 78, -100],
type: 'bar'
}, {
yAxisID: 'y2',
data: [-1000, 1000],
}, {
yAxisID: 'y',
data: [150, 0, 0, -100, -10, 9],
type: 'bar'
}, {
yAxisID: 'y',
data: [10, 10, 10, 10, 10, 10],
type: 'line'
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
stacked: true
},
y2: {
position: 'right',
type: 'linear'
}
}
}
});
chart.update();
expect(chart.scales.y.min).toBe(-150);
expect(chart.scales.y.max).toBe(200);
});
it('Should correctly determine the min and max data values when stacked mode is turned on and there are hidden datasets', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 0, -5, 78, -100],
}, {
yAxisID: 'y2',
data: [-1000, 1000],
}, {
yAxisID: 'y',
data: [150, 0, 0, -100, -10, 9],
}, {
yAxisID: 'y',
data: [10, 20, 30, 40, 50, 60],
hidden: true
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
stacked: true
},
y2: {
position: 'right',
type: 'linear'
}
}
}
});
chart.update();
expect(chart.scales.y.min).toBe(-150);
expect(chart.scales.y.max).toBe(200);
});
it('Should correctly determine the min and max data values when stacked mode is turned on there are multiple types of datasets', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
type: 'bar',
data: [10, 5, 0, -5, 78, -100]
}, {
type: 'line',
data: [10, 10, 10, 10, 10, 10],
}, {
type: 'bar',
data: [150, 0, 0, -100, -10, 9]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
stacked: true
}
}
}
});
chart.scales.y.determineDataLimits();
expect(chart.scales.y.min).toBe(-105);
expect(chart.scales.y.max).toBe(160);
});
it('Should ensure that the scale has a max and min that are not equal', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(0);
expect(chart.scales.y.max).toBe(1);
});
it('Should ensure that the scale has a max and min that are not equal - large positive numbers', function() {
// https://github.com/chartjs/Chart.js/issues/9377
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
// Value larger than Number.MAX_SAFE_INTEGER
data: [10000000000000000]
}],
labels: ['a']
},
options: {
scales: {
y: {
type: 'linear'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(10000000000000000 * 0.95);
expect(chart.scales.y.max).toBe(10000000000000000 * 1.05);
});
it('Should ensure that the scale has a max and min that are not equal - large negative numbers', function() {
// https://github.com/chartjs/Chart.js/issues/9377
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
// Value larger than Number.MAX_SAFE_INTEGER
data: [-10000000000000000]
}],
labels: ['a']
},
options: {
scales: {
y: {
type: 'linear'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.max).toBe(-10000000000000000 * 0.95);
expect(chart.scales.y.min).toBe(-10000000000000000 * 1.05);
});
it('Should ensure that the scale has a max and min that are not equal when beginAtZero is set', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
beginAtZero: true
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(0);
expect(chart.scales.y.max).toBe(1);
});
it('Should use the suggestedMin and suggestedMax options', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [1, 1, 1, 2, 1, 0]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
suggestedMax: 10,
suggestedMin: -10
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(-10);
expect(chart.scales.y.max).toBe(10);
});
it('Should use the min and max options', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [1, 1, 1, 2, 1, 0]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
max: 1010,
min: -1010
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(-1010);
expect(chart.scales.y.max).toBe(1010);
var labels = getLabels(chart.scales.y);
expect(labels[0]).toBe('-1,010');
expect(labels[labels.length - 1]).toBe('1,010');
});
it('Should use min, max and stepSize to create fixed spaced ticks', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 3, 6, 8, 3, 1]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
min: 1,
max: 11,
ticks: {
stepSize: 2
}
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(1);
expect(chart.scales.y.max).toBe(11);
expect(getLabels(chart.scales.y)).toEqual(['1', '3', '5', '7', '9', '11']);
});
it('Should not generate any ticks > max if max is specified', function() {
var chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'linear',
min: 2.404e-8,
max: 2.4143e-8,
ticks: {
includeBounds: false,
},
},
},
},
});
expect(chart.scales.x.min).toBe(2.404e-8);
expect(chart.scales.x.max).toBe(2.4143e-8);
expect(chart.scales.x.ticks[chart.scales.x.ticks.length - 1].value).toBeLessThanOrEqual(2.4143e-8);
});
it('Should not generate insane amounts of ticks with small stepSize and large range', function() {
var chart = window.acquireChart({
type: 'bar',
options: {
scales: {
y: {
type: 'linear',
min: 1,
max: 1E10,
ticks: {
stepSize: 2,
autoSkip: false
}
}
}
}
});
expect(chart.scales.y.min).toBe(1);
expect(chart.scales.y.max).toBe(1E10);
expect(chart.scales.y.ticks.length).toBeLessThanOrEqual(1000);
});
it('Should create decimal steps if stepSize is a decimal number', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 3, 6, 8, 3, 1]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
ticks: {
stepSize: 2.5
}
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(0);
expect(chart.scales.y.max).toBe(10);
expect(getLabels(chart.scales.y)).toEqual(['0', '2.5', '5', '7.5', '10']);
});
describe('precision', function() {
it('Should create integer steps if precision is 0', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [0, 1, 2, 1, 0, 1]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
ticks: {
precision: 0
}
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(0);
expect(chart.scales.y.max).toBe(2);
expect(getLabels(chart.scales.y)).toEqual(['0', '1', '2']);
});
it('Should round the step size to the given number of decimal places', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [0, 0.001, 0.002, 0.003, 0, 0.001]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'linear',
ticks: {
precision: 2
}
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(0);
expect(chart.scales.y.max).toBe(0.01);
expect(getLabels(chart.scales.y)).toEqual(['0', '0.01']);
});
});
it('should forcibly include 0 in the range if the beginAtZero option is used', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [20, 30, 40, 50]
}],
labels: ['a', 'b', 'c', 'd']
},
options: {
scales: {
y: {
type: 'linear',
beginAtZero: false
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(getLabels(chart.scales.y)).toEqual(['20', '25', '30', '35', '40', '45', '50']);
chart.scales.y.options.beginAtZero = true;
chart.update();
expect(getLabels(chart.scales.y)).toEqual(['0', '5', '10', '15', '20', '25', '30', '35', '40', '45', '50']);
chart.data.datasets[0].data = [-20, -30, -40, -50];
chart.update();
expect(getLabels(chart.scales.y)).toEqual(['-50', '-45', '-40', '-35', '-30', '-25', '-20', '-15', '-10', '-5', '0']);
chart.scales.y.options.beginAtZero = false;
chart.update();
expect(getLabels(chart.scales.y)).toEqual(['-50', '-45', '-40', '-35', '-30', '-25', '-20']);
});
it('Should generate tick marks in the correct order in reversed mode', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 0, 25, 78]
}],
labels: ['a', 'b', 'c', 'd']
},
options: {
scales: {
y: {
type: 'linear',
reverse: true
}
}
}
});
expect(getLabels(chart.scales.y)).toEqual(['80', '70', '60', '50', '40', '30', '20', '10', '0']);
expect(chart.scales.y.start).toBe(80);
expect(chart.scales.y.end).toBe(0);
});
it('should use the correct number of decimal places in the default format function', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [0.06, 0.005, 0, 0.025, 0.0078]
}],
labels: ['a', 'b', 'c', 'd']
},
options: {
scales: {
y: {
type: 'linear',
}
}
}
});
expect(getLabels(chart.scales.y)).toEqual(['0', '0.01', '0.02', '0.03', '0.04', '0.05', '0.06']);
});
it('Should correctly limit the maximum number of ticks', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
labels: ['a', 'b'],
datasets: [{
data: [0.5, 2.5]
}]
},
options: {
scales: {
y: {
beginAtZero: false
}
}
}
});
expect(getLabels(chart.scales.y)).toEqual(['0.5', '1.0', '1.5', '2.0', '2.5']);
chart.options.scales.y.ticks.maxTicksLimit = 11;
chart.update();
expect(getLabels(chart.scales.y)).toEqual(['0.5', '1.0', '1.5', '2.0', '2.5']);
chart.options.scales.y.ticks.maxTicksLimit = 21;
chart.update();
expect(getLabels(chart.scales.y)).toEqual([
'0.5',
'0.6', '0.7', '0.8', '0.9', '1.0', '1.1', '1.2', '1.3', '1.4', '1.5',
'1.6', '1.7', '1.8', '1.9', '2.0', '2.1', '2.2', '2.3', '2.4', '2.5'
]);
chart.options.scales.y.ticks.maxTicksLimit = 11;
chart.options.scales.y.ticks.stepSize = 0.01;
chart.update();
expect(getLabels(chart.scales.y)).toEqual(['0.5', '1.0', '1.5', '2.0', '2.5']);
chart.options.scales.y.min = 0.3;
chart.options.scales.y.max = 2.8;
chart.update();
expect(getLabels(chart.scales.y)).toEqual(['0.3', '0.8', '1.3', '1.8', '2.3', '2.8']);
});
it('Should bound to data', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: ['a', 'b'],
datasets: [{
data: [1, 99]
}]
},
options: {
scales: {
y: {
bounds: 'data'
}
}
}
});
expect(chart.scales.y.min).toEqual(1);
expect(chart.scales.y.max).toEqual(99);
});
it('Should build labels using the user supplied callback', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 0, 25, 78]
}],
labels: ['a', 'b', 'c', 'd']
},
options: {
scales: {
y: {
type: 'linear',
ticks: {
callback: function(value, index) {
return index.toString();
}
}
}
}
}
});
// Just the index
expect(getLabels(chart.scales.y)).toEqual(['0', '1', '2', '3', '4', '5', '6', '7', '8']);
});
it('Should get the correct pixel value for a point', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: [-1, 1],
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [-1, 1]
}],
},
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
var xScale = chart.scales.x;
expect(xScale.getPixelForValue(1)).toBeCloseToPixel(501); // right - paddingRight
expect(xScale.getPixelForValue(-1)).toBeCloseToPixel(31 + 3); // left + paddingLeft + tick padding
expect(xScale.getPixelForValue(0)).toBeCloseToPixel(266 + 3 / 2); // halfway*/
expect(xScale.getValueForPixel(501)).toBeCloseTo(1, 1e-2);
expect(xScale.getValueForPixel(31)).toBeCloseTo(-1, 1e-2);
expect(xScale.getValueForPixel(266)).toBeCloseTo(0, 1e-2);
var yScale = chart.scales.y;
expect(yScale.getPixelForValue(1)).toBeCloseToPixel(32); // right - paddingRight
expect(yScale.getPixelForValue(-1)).toBeCloseToPixel(484); // left + paddingLeft
expect(yScale.getPixelForValue(0)).toBeCloseToPixel(258); // halfway*/
expect(yScale.getValueForPixel(32)).toBeCloseTo(1, 1e-2);
expect(yScale.getValueForPixel(484)).toBeCloseTo(-1, 1e-2);
expect(yScale.getValueForPixel(258)).toBeCloseTo(0, 1e-2);
});
it('should fit correctly', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [{
x: 10,
y: 100
}, {
x: -10,
y: 0
}, {
x: 0,
y: 0
}, {
x: 99,
y: 7
}]
}],
},
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
var xScale = chart.scales.x;
var yScale = chart.scales.y;
expect(xScale.paddingTop).toBeCloseToPixel(0);
expect(xScale.paddingBottom).toBeCloseToPixel(0);
expect(xScale.paddingLeft).toBeCloseToPixel(12);
expect(xScale.paddingRight).toBeCloseToPixel(13.5);
expect(xScale.width).toBeCloseToPixel(468 - 3); // minus tick padding
expect(xScale.height).toBeCloseToPixel(30);
expect(yScale.paddingTop).toBeCloseToPixel(10);
expect(yScale.paddingBottom).toBeCloseToPixel(10);
expect(yScale.paddingLeft).toBeCloseToPixel(0);
expect(yScale.paddingRight).toBeCloseToPixel(0);
expect(yScale.width).toBeCloseToPixel(31 + 3); // plus tick padding
expect(yScale.height).toBeCloseToPixel(450);
// Extra size when scale label showing
xScale.options.title.display = true;
yScale.options.title.display = true;
chart.update();
expect(xScale.paddingTop).toBeCloseToPixel(0);
expect(xScale.paddingBottom).toBeCloseToPixel(0);
expect(xScale.paddingLeft).toBeCloseToPixel(12);
expect(xScale.paddingRight).toBeCloseToPixel(13.5);
expect(xScale.width).toBeCloseToPixel(442);
expect(xScale.height).toBeCloseToPixel(50);
expect(yScale.paddingTop).toBeCloseToPixel(10);
expect(yScale.paddingBottom).toBeCloseToPixel(10);
expect(yScale.paddingLeft).toBeCloseToPixel(0);
expect(yScale.paddingRight).toBeCloseToPixel(0);
expect(yScale.width).toBeCloseToPixel(58);
expect(yScale.height).toBeCloseToPixel(429);
});
it('should fit correctly when display is turned off', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [{
x: 10,
y: 100
}, {
x: -10,
y: 0
}, {
x: 0,
y: 0
}, {
x: 99,
y: 7
}]
}],
},
options: {
scales: {
x: {
type: 'linear',
position: 'bottom'
},
y: {
type: 'linear',
grid: {
drawTicks: false,
},
border: {
display: false
},
title: {
display: false,
lineHeight: 1.2
},
ticks: {
display: false,
padding: 0
}
}
}
}
});
var yScale = chart.scales.y;
expect(yScale.width).toBeCloseToPixel(0);
});
it('max and min value should be valid and finite when charts datasets are hidden', function() {
var barData = {
labels: ['S1', 'S2', 'S3'],
datasets: [{
label: 'Closed',
backgroundColor: '#382765',
data: [2500, 2000, 1500]
}, {
label: 'In Progress',
backgroundColor: '#7BC225',
data: [1000, 2000, 1500]
}, {
label: 'Assigned',
backgroundColor: '#ffC225',
data: [1000, 2000, 1500]
}]
};
var chart = window.acquireChart({
type: 'bar',
data: barData,
options: {
indexAxis: 'y',
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
}
}
});
barData.datasets.forEach(function(data, index) {
var meta = chart.getDatasetMeta(index);
meta.hidden = true;
chart.update();
});
expect(chart.scales.x.min).toEqual(0);
expect(chart.scales.x.max).toEqual(1);
});
it('max and min value should be valid when min is set and all datasets are hidden', function() {
var barData = {
labels: ['S1', 'S2', 'S3'],
datasets: [{
label: 'dataset 1',
backgroundColor: '#382765',
data: [2500, 2000, 1500],
hidden: true,
}]
};
var chart = window.acquireChart({
type: 'bar',
data: barData,
options: {
indexAxis: 'y',
scales: {
x: {
min: 20
}
}
}
});
expect(chart.scales.x.min).toEqual(20);
expect(chart.scales.x.max).toEqual(21);
});
it('min settings should be used if set to zero', function() {
var barData = {
labels: ['S1', 'S2', 'S3'],
datasets: [{
label: 'dataset 1',
backgroundColor: '#382765',
data: [2500, 2000, 1500]
}]
};
var chart = window.acquireChart({
type: 'bar',
data: barData,
options: {
indexAxis: 'y',
scales: {
x: {
min: 0,
max: 3000
}
}
}
});
expect(chart.scales.x.min).toEqual(0);
});
it('max settings should be used if set to zero', function() {
var barData = {
labels: ['S1', 'S2', 'S3'],
datasets: [{
label: 'dataset 1',
backgroundColor: '#382765',
data: [-2500, -2000, -1500]
}]
};
var chart = window.acquireChart({
type: 'bar',
data: barData,
options: {
indexAxis: 'y',
scales: {
x: {
min: -3000,
max: 0
}
}
}
});
expect(chart.scales.x.max).toEqual(0);
});
it('Should get correct pixel values when horizontal', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [0.05, -25, 10, 15, 20, 25, 30, 35]
}]
},
options: {
indexAxis: 'y',
scales: {
x: {
type: 'linear',
}
}
}
});
var start = chart.chartArea.left;
var end = chart.chartArea.right;
var min = -30;
var max = 40;
var scale = chart.scales.x;
expect(scale.getPixelForValue(max)).toBeCloseToPixel(end);
expect(scale.getPixelForValue(min)).toBeCloseToPixel(start);
expect(scale.getValueForPixel(end)).toBeCloseTo(max, 4);
expect(scale.getValueForPixel(start)).toBeCloseTo(min, 4);
scale.options.reverse = true;
chart.update();
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | true |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.plugin.tests.js | test/specs/core.plugin.tests.js | describe('Chart.plugins', function() {
describe('Chart.notifyPlugins', function() {
it('should call inline plugins with arguments', function() {
var plugin = {hook: function() {}};
var chart = window.acquireChart({
plugins: [plugin]
});
var args = {value: 42};
spyOn(plugin, 'hook');
chart.notifyPlugins('hook', args);
expect(plugin.hook.calls.count()).toBe(1);
expect(plugin.hook.calls.first().args[0]).toBe(chart);
expect(plugin.hook.calls.first().args[1]).toBe(args);
expect(plugin.hook.calls.first().args[2]).toEqualOptions({});
});
it('should call global plugins with arguments', function() {
var plugin = {id: 'a', hook: function() {}};
var chart = window.acquireChart({});
var args = {value: 42};
spyOn(plugin, 'hook');
Chart.register(plugin);
chart.notifyPlugins('hook', args);
expect(plugin.hook.calls.count()).toBe(1);
expect(plugin.hook.calls.first().args[0]).toBe(chart);
expect(plugin.hook.calls.first().args[1]).toBe(args);
expect(plugin.hook.calls.first().args[2]).toEqualOptions({});
Chart.unregister(plugin);
});
it('should call plugin only once even if registered multiple times', function() {
var plugin = {id: 'test', hook: function() {}};
var chart = window.acquireChart({
plugins: [plugin, plugin]
});
spyOn(plugin, 'hook');
Chart.register([plugin, plugin]);
chart.notifyPlugins('hook');
expect(plugin.hook.calls.count()).toBe(1);
Chart.unregister(plugin);
});
it('should call plugins in the correct order (global first)', function() {
var results = [];
var chart = window.acquireChart({
plugins: [{
hook: function() {
results.push(1);
}
}, {
hook: function() {
results.push(2);
}
}, {
hook: function() {
results.push(3);
}
}]
});
var plugins = [{
id: 'a',
hook: function() {
results.push(4);
}
}, {
id: 'b',
hook: function() {
results.push(5);
}
}, {
id: 'c',
hook: function() {
results.push(6);
}
}];
Chart.register(plugins);
var ret = chart.notifyPlugins('hook');
expect(ret).toBeTruthy();
expect(results).toEqual([4, 5, 6, 1, 2, 3]);
Chart.unregister(plugins);
});
it('should return TRUE if no plugin explicitly returns FALSE', function() {
var chart = window.acquireChart({
plugins: [{
hook: function() {}
}, {
hook: function() {
return null;
}
}, {
hook: function() {
return 0;
}
}, {
hook: function() {
return true;
}
}, {
hook: function() {
return 1;
}
}]
});
var plugins = chart.config.plugins;
plugins.forEach(function(plugin) {
spyOn(plugin, 'hook').and.callThrough();
});
var ret = chart.notifyPlugins('hook');
expect(ret).toBeTruthy();
plugins.forEach(function(plugin) {
expect(plugin.hook).toHaveBeenCalled();
});
});
it('should return FALSE if any plugin explicitly returns FALSE', function() {
var chart = window.acquireChart({
plugins: [{
hook: function() {}
}, {
hook: function() {
return null;
}
}, {
hook: function() {
return false;
}
}, {
hook: function() {
return 42;
}
}, {
hook: function() {
return 'bar';
}
}]
});
var plugins = chart.config.plugins;
plugins.forEach(function(plugin) {
spyOn(plugin, 'hook').and.callThrough();
});
var ret = chart.notifyPlugins('hook', {cancelable: true});
expect(ret).toBeFalsy();
expect(plugins[0].hook).toHaveBeenCalled();
expect(plugins[1].hook).toHaveBeenCalled();
expect(plugins[2].hook).toHaveBeenCalled();
expect(plugins[3].hook).not.toHaveBeenCalled();
expect(plugins[4].hook).not.toHaveBeenCalled();
});
});
describe('config.options.plugins', function() {
it('should call plugins with options at last argument', function() {
var plugin = {id: 'foo', hook: function() {}};
var chart = window.acquireChart({
options: {
plugins: {
foo: {a: '123'},
}
}
});
spyOn(plugin, 'hook');
Chart.register(plugin);
chart.notifyPlugins('hook');
chart.notifyPlugins('hook', {arg1: 'bla'});
chart.notifyPlugins('hook', {arg1: 'bla', arg2: 42});
expect(plugin.hook.calls.count()).toBe(3);
expect(plugin.hook.calls.argsFor(0)[2]).toEqualOptions({a: '123'});
expect(plugin.hook.calls.argsFor(1)[2]).toEqualOptions({a: '123'});
expect(plugin.hook.calls.argsFor(2)[2]).toEqualOptions({a: '123'});
Chart.unregister(plugin);
});
it('should call plugins with options associated to their identifier', function() {
var plugins = {
a: {id: 'a', hook: function() {}},
b: {id: 'b', hook: function() {}},
c: {id: 'c', hook: function() {}}
};
Chart.register(plugins.a);
var chart = window.acquireChart({
plugins: [plugins.b, plugins.c],
options: {
plugins: {
a: {a: '123'},
b: {b: '456'},
c: {c: '789'}
}
}
});
spyOn(plugins.a, 'hook');
spyOn(plugins.b, 'hook');
spyOn(plugins.c, 'hook');
chart.notifyPlugins('hook');
expect(plugins.a.hook).toHaveBeenCalled();
expect(plugins.b.hook).toHaveBeenCalled();
expect(plugins.c.hook).toHaveBeenCalled();
expect(plugins.a.hook.calls.first().args[2]).toEqualOptions({a: '123'});
expect(plugins.b.hook.calls.first().args[2]).toEqualOptions({b: '456'});
expect(plugins.c.hook.calls.first().args[2]).toEqualOptions({c: '789'});
Chart.unregister(plugins.a);
});
it('should not call plugins when config.options.plugins.{id} is FALSE', function() {
var plugins = {
a: {id: 'a', hook: function() {}},
b: {id: 'b', hook: function() {}},
c: {id: 'c', hook: function() {}}
};
Chart.register(plugins.a);
var chart = window.acquireChart({
plugins: [plugins.b, plugins.c],
options: {
plugins: {
a: false,
b: false
}
}
});
spyOn(plugins.a, 'hook');
spyOn(plugins.b, 'hook');
spyOn(plugins.c, 'hook');
chart.notifyPlugins('hook');
expect(plugins.a.hook).not.toHaveBeenCalled();
expect(plugins.b.hook).not.toHaveBeenCalled();
expect(plugins.c.hook).toHaveBeenCalled();
Chart.unregister(plugins.a);
});
it('should call plugins with default options when plugin options is TRUE', function() {
var plugin = {id: 'a', hook: function() {}, defaults: {a: 42}};
Chart.register(plugin);
var chart = window.acquireChart({
options: {
plugins: {
a: true
}
}
});
spyOn(plugin, 'hook');
chart.notifyPlugins('hook');
expect(plugin.hook).toHaveBeenCalled();
expect(Object.keys(plugin.hook.calls.first().args[2])).toEqual(['a']);
expect(plugin.hook.calls.first().args[2]).toEqual(jasmine.objectContaining({a: 42}));
Chart.unregister(plugin);
});
it('should call plugins with default options if plugin config options is undefined', function() {
var plugin = {id: 'a', hook: function() {}, defaults: {a: 'foobar'}};
Chart.register(plugin);
spyOn(plugin, 'hook');
var chart = window.acquireChart();
chart.notifyPlugins('hook');
expect(plugin.hook).toHaveBeenCalled();
expect(plugin.hook.calls.first().args[2]).toEqualOptions({a: 'foobar'});
Chart.unregister(plugin);
});
// https://github.com/chartjs/Chart.js/issues/10482
it('should resolve defaults for local plugins', function() {
var plugin = {id: 'a', hook: function() {}, defaults: {bar: 'bar'}};
var chart = window.acquireChart({
plugins: [plugin],
options: {
plugins: {
a: {
foo: 'foo'
}
}
},
});
spyOn(plugin, 'hook');
chart.notifyPlugins('hook');
expect(plugin.hook).toHaveBeenCalled();
expect(plugin.hook.calls.first().args[2]).toEqualOptions({foo: 'foo', bar: 'bar'});
Chart.unregister(plugin);
});
// https://github.com/chartjs/Chart.js/issues/5111#issuecomment-355934167
it('should update plugin options', function() {
var plugin = {id: 'a', hook: function() {}};
var chart = window.acquireChart({
plugins: [plugin],
options: {
plugins: {
a: {
foo: 'foo'
}
}
},
});
spyOn(plugin, 'hook');
chart.notifyPlugins('hook');
expect(plugin.hook).toHaveBeenCalled();
expect(plugin.hook.calls.first().args[2]).toEqualOptions({foo: 'foo'});
chart.options.plugins.a = {bar: 'bar'};
chart.update();
plugin.hook.calls.reset();
chart.notifyPlugins('hook');
expect(plugin.hook).toHaveBeenCalled();
expect(plugin.hook.calls.first().args[2]).toEqualOptions({bar: 'bar'});
});
// https://github.com/chartjs/Chart.js/issues/10654
it('should resolve options even if some subnodes are set as undefined', function() {
var runtimeOptions;
var plugin = {
id: 'a',
afterUpdate: function(chart, args, options) {
options.l1.l2.l3.display = true;
runtimeOptions = options;
},
defaults: {
l1: {
l2: {
l3: {
display: false
}
}
}
}
};
window.acquireChart({
plugins: [plugin],
options: {
plugins: {
a: {
l1: {
l2: undefined
}
},
}
},
});
expect(runtimeOptions.l1.l2.l3.display).toBe(true);
Chart.unregister(plugin);
});
it('should disable all plugins', function() {
var plugin = {id: 'a', hook: function() {}};
var chart = window.acquireChart({
plugins: [plugin],
options: {
plugins: false
}
});
spyOn(plugin, 'hook');
chart.notifyPlugins('hook');
expect(plugin.hook).not.toHaveBeenCalled();
});
it('should not restart plugins when a double register occurs', function() {
var results = [];
var chart = window.acquireChart({
plugins: [{
start: function() {
results.push(1);
}
}]
});
Chart.register({id: 'abc', hook: function() {}});
Chart.register({id: 'def', hook: function() {}});
chart.update();
// The plugin on the chart should only be started once
expect(results).toEqual([1]);
});
it('should default to false for _scriptable, _indexable', function(done) {
const plugin = {
id: 'test',
start: function(chart, args, opts) {
expect(opts.fun).toEqual(jasmine.any(Function));
expect(opts.fun()).toEqual('test');
expect(opts.arr).toEqual([1, 2, 3]);
expect(opts.sub.subfun).toEqual(jasmine.any(Function));
expect(opts.sub.subfun()).toEqual('subtest');
expect(opts.sub.subarr).toEqual([3, 2, 1]);
done();
}
};
window.acquireChart({
options: {
plugins: {
test: {
fun: () => 'test',
arr: [1, 2, 3],
sub: {
subfun: () => 'subtest',
subarr: [3, 2, 1],
}
}
}
},
plugins: [plugin]
});
});
it('should filter event callbacks by plugin events array', async function() {
const results = [];
const chart = window.acquireChart({
options: {
events: ['mousemove', 'test', 'test2', 'pointerleave'],
plugins: {
testPlugin: {
events: ['test', 'pointerleave']
}
}
},
plugins: [{
id: 'testPlugin',
beforeEvent: function(_chart, args) {
results.push('before' + args.event.type);
},
afterEvent: function(_chart, args) {
results.push('after' + args.event.type);
}
}]
});
await jasmine.triggerMouseEvent(chart, 'mousemove', {x: 0, y: 0});
await jasmine.triggerMouseEvent(chart, 'test', {x: 0, y: 0});
await jasmine.triggerMouseEvent(chart, 'test2', {x: 0, y: 0});
await jasmine.triggerMouseEvent(chart, 'pointerleave', {x: 0, y: 0});
expect(results).toEqual(['beforetest', 'aftertest', 'beforemouseout', 'aftermouseout']);
});
it('should not call plugins after uninstall', async function() {
const results = [];
const chart = window.acquireChart({
options: {
events: ['test'],
plugins: {
testPlugin: {
events: ['test']
}
}
},
plugins: [{
id: 'testPlugin',
reset: () => results.push('reset'),
afterDestroy: () => results.push('afterDestroy'),
uninstall: () => results.push('uninstall'),
}]
});
chart.reset();
expect(results).toEqual(['reset']);
chart.destroy();
expect(results).toEqual(['reset', 'afterDestroy', 'uninstall']);
chart.reset();
expect(results).toEqual(['reset', 'afterDestroy', 'uninstall']);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/global.defaults.tests.js | test/specs/global.defaults.tests.js | describe('Default Configs', function() {
describe('Doughnut Chart', function() {
it('should return correct legend label objects', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
labels: ['label1', 'label2', 'label3'],
datasets: [{
data: [10, 20, NaN],
backgroundColor: ['red', 'green', 'blue'],
borderWidth: 2,
borderColor: '#000'
}]
},
});
var expectedCommon = {
fontColor: '#666',
hidden: false,
strokeStyle: '#000',
textAlign: undefined,
lineWidth: 2,
pointStyle: undefined,
lineDash: [],
lineDashOffset: 0,
lineJoin: undefined,
borderRadius: undefined,
};
var expected = [{
text: 'label1',
fillStyle: 'red',
index: 0,
...expectedCommon,
}, {
text: 'label2',
fillStyle: 'green',
index: 1,
...expectedCommon,
}, {
text: 'label3',
fillStyle: 'blue',
index: 2,
...expectedCommon,
}];
expect(chart.legend.legendItems).toEqual(expected);
});
it('should return correct legend label objects with border radius', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
labels: ['label1'],
datasets: [{
data: [10],
backgroundColor: ['red'],
borderWidth: 2,
borderColor: '#000',
borderDash: [1, 2, 3],
borderDashOffset: 1,
borderJoinStyle: 'miter',
borderRadius: 3,
}]
},
options: {
plugins: {
legend: {
labels: {
useBorderRadius: true,
borderRadius: 5,
textAlign: 'left',
}
}
}
}
});
var expected = [{
text: 'label1',
fillStyle: 'red',
index: 0,
fontColor: '#666',
hidden: false,
strokeStyle: '#000',
textAlign: 'left',
lineWidth: 2,
pointStyle: undefined,
lineDash: [1, 2, 3],
lineDashOffset: 1,
lineJoin: 'miter',
borderRadius: 5
}];
expect(chart.legend.legendItems).toEqual(expected);
});
it('should hide the correct arc when a legend item is clicked', function() {
var config = Chart.overrides.doughnut;
var chart = window.acquireChart({
type: 'doughnut',
data: {
labels: ['label1', 'label2', 'label3'],
datasets: [{
data: [10, 20, NaN],
backgroundColor: ['red', 'green', 'blue'],
borderWidth: 2,
borderColor: '#000'
}]
},
});
spyOn(chart, 'update').and.callThrough();
var legendItem = chart.legend.legendItems[0];
config.plugins.legend.onClick(null, legendItem, chart.legend);
expect(chart.getDataVisibility(0)).toBe(false);
expect(chart.update).toHaveBeenCalled();
config.plugins.legend.onClick(null, legendItem, chart.legend);
expect(chart.getDataVisibility(0)).toBe(true);
});
});
describe('Polar Area Chart', function() {
it('should return correct legend label objects', function() {
var chart = window.acquireChart({
type: 'polarArea',
data: {
labels: ['label1', 'label2', 'label3'],
datasets: [{
data: [10, 20, NaN],
backgroundColor: ['red', 'green', 'blue'],
borderWidth: 2,
borderColor: '#000'
}]
},
});
var expected = [{
text: 'label1',
fillStyle: 'red',
fontColor: '#666',
hidden: false,
index: 0,
strokeStyle: '#000',
textAlign: undefined,
lineWidth: 2,
pointStyle: undefined
}, {
text: 'label2',
fillStyle: 'green',
fontColor: '#666',
hidden: false,
index: 1,
strokeStyle: '#000',
textAlign: undefined,
lineWidth: 2,
pointStyle: undefined
}, {
text: 'label3',
fillStyle: 'blue',
fontColor: '#666',
hidden: false,
index: 2,
strokeStyle: '#000',
textAlign: undefined,
lineWidth: 2,
pointStyle: undefined
}];
expect(chart.legend.legendItems).toEqual(expected);
});
it('should hide the correct arc when a legend item is clicked', function() {
var config = Chart.overrides.polarArea;
var chart = window.acquireChart({
type: 'polarArea',
data: {
labels: ['label1', 'label2', 'label3'],
datasets: [{
data: [10, 20, NaN],
backgroundColor: ['red', 'green', 'blue'],
borderWidth: 2,
borderColor: '#000'
}]
},
});
spyOn(chart, 'update').and.callThrough();
var legendItem = chart.legend.legendItems[0];
config.plugins.legend.onClick(null, legendItem, chart.legend);
expect(chart.getDataVisibility(0)).toBe(false);
expect(chart.update).toHaveBeenCalled();
config.plugins.legend.onClick(null, legendItem, chart.legend);
expect(chart.getDataVisibility(0)).toBe(true);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.easing.tests.js | test/specs/helpers.easing.tests.js | 'use strict';
describe('Chart.helpers.easingEffects', function() {
var helpers = Chart.helpers;
describe('effects', function() {
var expected = {
easeInOutBack: [-0, -0.03751855, -0.09255566, -0.07883348, 0.08992579, 0.5, 0.91007421, 1.07883348, 1.09255566, 1.03751855, 1],
easeInOutBounce: [0, 0.03, 0.11375, 0.045, 0.34875, 0.5, 0.65125, 0.955, 0.88625, 0.97, 1],
easeInOutCirc: [-0, 0.01010205, 0.04174243, 0.1, 0.2, 0.5, 0.8, 0.9, 0.95825757, 0.98989795, 1],
easeInOutCubic: [0, 0.004, 0.032, 0.108, 0.256, 0.5, 0.744, 0.892, 0.968, 0.996, 1],
easeInOutElastic: [0, 0.00033916, -0.00390625, 0.02393889, -0.11746158, 0.5, 1.11746158, 0.97606111, 1.00390625, 0.99966084, 1],
easeInOutExpo: [0, 0.00195313, 0.0078125, 0.03125, 0.125, 0.5, 0.875, 0.96875, 0.9921875, 0.99804688, 1],
easeInOutQuad: [0, 0.02, 0.08, 0.18, 0.32, 0.5, 0.68, 0.82, 0.92, 0.98, 1],
easeInOutQuart: [0, 0.0008, 0.0128, 0.0648, 0.2048, 0.5, 0.7952, 0.9352, 0.9872, 0.9992, 1],
easeInOutQuint: [0, 0.00016, 0.00512, 0.03888, 0.16384, 0.5, 0.83616, 0.96112, 0.99488, 0.99984, 1],
easeInOutSine: [-0, 0.02447174, 0.0954915, 0.20610737, 0.3454915, 0.5, 0.6545085, 0.79389263, 0.9045085, 0.97552826, 1],
easeInBack: [-0, -0.01431422, -0.04645056, -0.08019954, -0.09935168, -0.0876975, -0.02902752, 0.09286774, 0.29419776, 0.59117202, 1],
easeInBounce: [0, 0.011875, 0.06, 0.069375, 0.2275, 0.234375, 0.09, 0.319375, 0.6975, 0.924375, 1],
easeInCirc: [-0, 0.00501256, 0.0202041, 0.0460608, 0.08348486, 0.1339746, 0.2, 0.28585716, 0.4, 0.56411011, 1],
easeInCubic: [0, 0.001, 0.008, 0.027, 0.064, 0.125, 0.216, 0.343, 0.512, 0.729, 1],
easeInExpo: [0, 0.00195313, 0.00390625, 0.0078125, 0.015625, 0.03125, 0.0625, 0.125, 0.25, 0.5, 1],
easeInElastic: [0, 0.00195313, -0.00195313, -0.00390625, 0.015625, -0.015625, -0.03125, 0.125, -0.125, -0.25, 1],
easeInQuad: [0, 0.01, 0.04, 0.09, 0.16, 0.25, 0.36, 0.49, 0.64, 0.81, 1],
easeInQuart: [0, 0.0001, 0.0016, 0.0081, 0.0256, 0.0625, 0.1296, 0.2401, 0.4096, 0.6561, 1],
easeInQuint: [0, 0.00001, 0.00032, 0.00243, 0.01024, 0.03125, 0.07776, 0.16807, 0.32768, 0.59049, 1],
easeInSine: [0, 0.01231166, 0.04894348, 0.10899348, 0.19098301, 0.29289322, 0.41221475, 0.5460095, 0.69098301, 0.84356553, 1],
easeOutBack: [0, 0.40882798, 0.70580224, 0.90713226, 1.02902752, 1.0876975, 1.09935168, 1.08019954, 1.04645056, 1.01431422, 1],
easeOutBounce: [0, 0.075625, 0.3025, 0.680625, 0.91, 0.765625, 0.7725, 0.930625, 0.94, 0.988125, 1],
easeOutCirc: [0, 0.43588989, 0.6, 0.71414284, 0.8, 0.8660254, 0.91651514, 0.9539392, 0.9797959, 0.99498744, 1],
easeOutElastic: [0, 1.25, 1.125, 0.875, 1.03125, 1.015625, 0.984375, 1.00390625, 1.00195313, 0.99804688, 1],
easeOutExpo: [0, 0.5, 0.75, 0.875, 0.9375, 0.96875, 0.984375, 0.9921875, 0.99609375, 0.99804688, 1],
easeOutCubic: [0, 0.271, 0.488, 0.657, 0.784, 0.875, 0.936, 0.973, 0.992, 0.999, 1],
easeOutQuad: [0, 0.19, 0.36, 0.51, 0.64, 0.75, 0.84, 0.91, 0.96, 0.99, 1],
easeOutQuart: [-0, 0.3439, 0.5904, 0.7599, 0.8704, 0.9375, 0.9744, 0.9919, 0.9984, 0.9999, 1],
easeOutQuint: [0, 0.40951, 0.67232, 0.83193, 0.92224, 0.96875, 0.98976, 0.99757, 0.99968, 0.99999, 1],
easeOutSine: [0, 0.15643447, 0.30901699, 0.4539905, 0.58778525, 0.70710678, 0.80901699, 0.89100652, 0.95105652, 0.98768834, 1],
linear: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
};
function generate(method) {
var fn = helpers.easingEffects[method];
var accuracy = Math.pow(10, 8);
var count = 10;
var values = [];
var i;
for (i = 0; i <= count; ++i) {
values.push(Math.round(accuracy * fn(i / count)) / accuracy);
}
return values;
}
Object.keys(helpers.easingEffects).forEach(function(method) {
it ('"' + method + '" should return expected values', function() {
expect(generate(method)).toEqual(expected[method]);
});
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.scale.tests.js | test/specs/core.scale.tests.js | function getLabels(scale) {
return scale.ticks.map(t => t.label);
}
describe('Core.scale', function() {
describe('auto', jasmine.fixture.specs('core.scale'));
it('should provide default scale label options', function() {
expect(Chart.defaults.scale.title).toEqual({
color: Chart.defaults.color,
display: false,
text: '',
padding: {
top: 4,
bottom: 4
}
});
});
describe('displaying xAxis ticks with autoSkip=true', function() {
function getChart(data) {
return window.acquireChart({
type: 'line',
data: data,
options: {
scales: {
x: {
ticks: {
autoSkip: true
}
}
}
}
});
}
function getChartBigData(maxTicksLimit) {
return window.acquireChart({
type: 'line',
data: {
labels: new Array(300).fill('red'),
datasets: [{
data: new Array(300).fill(5),
}]
},
options: {
scales: {
x: {
ticks: {
autoSkip: true,
maxTicksLimit
}
}
}
}
});
}
function lastTick(chart) {
var xAxis = chart.scales.x;
var ticks = xAxis.getTicks();
return ticks[ticks.length - 1];
}
it('should use autoSkip amount of ticks when maxTicksLimit is set to a larger number as autoSkip calculation', function() {
var chart = getChartBigData(300);
expect(chart.scales.x.ticks.length).toEqual(20);
});
it('should use maxTicksLimit amount of ticks when maxTicksLimit is set to a smaller number as autoSkip calculation', function() {
var chart = getChartBigData(3);
expect(chart.scales.x.ticks.length).toEqual(3);
});
it('should display the last tick if it fits evenly with other ticks', function() {
var chart = getChart({
labels: [
'January 2018', 'February 2018', 'March 2018', 'April 2018',
'May 2018', 'June 2018', 'July 2018', 'August 2018',
'September 2018'
],
datasets: [{
data: [12, 19, 3, 5, 2, 3, 7, 8, 9]
}]
});
expect(lastTick(chart).label).toEqual('September 2018');
});
it('should not display the last tick if it does not fit evenly', function() {
var chart = getChart({
labels: [
'January 2018', 'February 2018', 'March 2018', 'April 2018',
'May 2018', 'June 2018', 'July 2018', 'August 2018',
'September 2018', 'October 2018', 'November 2018', 'December 2018',
'January 2019', 'February 2019', 'March 2019', 'April 2019',
'May 2019', 'June 2019', 'July 2019', 'August 2019',
'September 2019', 'October 2019', 'November 2019', 'December 2019',
'January 2020', 'February 2020', 'March 2020', 'April 2020'
],
datasets: [{
data: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7]
}]
});
expect(lastTick(chart).label).toEqual('March 2020');
});
});
var gridLineTests = [{
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'],
offsetGridLines: false,
offset: false,
expected: [0.5, 128.5, 256.5, 384.5, 512.5]
}, {
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'],
offsetGridLines: false,
offset: true,
expected: [51.5, 153.5, 256.5, 358.5, 460.5]
}, {
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'],
offsetGridLines: true,
offset: false,
expected: [64.5, 192.5, 320.5, 448.5]
}, {
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'],
offsetGridLines: true,
offset: true,
expected: [0.5, 102.5, 204.5, 307.5, 409.5, 512.5]
}, {
labels: ['tick1'],
offsetGridLines: false,
offset: false,
expected: [0.5]
}, {
labels: ['tick1'],
offsetGridLines: false,
offset: true,
expected: [256.5]
}, {
labels: ['tick1'],
offsetGridLines: true,
offset: false,
expected: [512.5]
}, {
labels: ['tick1'],
offsetGridLines: true,
offset: true,
expected: [0.5, 512.5]
}];
gridLineTests.forEach(function(test) {
it('should get the correct pixels for gridLine(s) for the horizontal scale when offsetGridLines is ' + test.offsetGridLines + ' and offset is ' + test.offset, function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: []
}],
labels: test.labels
},
options: {
scales: {
x: {
grid: {
offset: test.offsetGridLines,
drawTicks: false
},
ticks: {
display: false
},
offset: test.offset
},
y: {
display: false
}
},
plugins: {
legend: false
}
}
});
var xScale = chart.scales.x;
xScale.ctx = window.createMockContext();
chart.draw();
expect(xScale.ctx.getCalls().filter(function(x) {
return x.name === 'moveTo' && x.args[1] === 0;
}).map(function(x) {
return x.args[0];
})).toEqual(test.expected);
});
});
gridLineTests.forEach(function(test) {
it('should get the correct pixels for gridLine(s) for the vertical scale when offsetGridLines is ' + test.offsetGridLines + ' and offset is ' + test.offset, function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: []
}],
labels: test.labels
},
options: {
scales: {
x: {
display: false
},
y: {
type: 'category',
grid: {
offset: test.offsetGridLines,
drawTicks: false
},
ticks: {
display: false
},
offset: test.offset
}
},
plugins: {
legend: false
}
}
});
var yScale = chart.scales.y;
yScale.ctx = window.createMockContext();
chart.draw();
expect(yScale.ctx.getCalls().filter(function(x) {
return x.name === 'moveTo' && x.args[0] === 1;
}).map(function(x) {
return x.args[1];
})).toEqual(test.expected);
});
});
it('should add the correct padding for long tick labels', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: [
'This is a very long label',
'This is a very long label'
],
datasets: [{
data: [0, 1]
}]
},
options: {
scales: {
y: {
display: false
}
},
plugins: {
legend: false
}
}
}, {
canvas: {
height: 100,
width: 200
}
});
var scale = chart.scales.x;
expect(scale.left).toBeGreaterThan(100);
expect(scale.right).toBeGreaterThan(190);
});
describe('given the axes display option is set to auto', function() {
describe('for the x axes', function() {
it('should draw the axes if at least one associated dataset is visible', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [100, 200, 100, 50],
xAxisId: 'foo',
hidden: true,
labels: ['Q1', 'Q2', 'Q3', 'Q4']
}, {
data: [100, 200, 100, 50],
xAxisId: 'foo',
labels: ['Q1', 'Q2', 'Q3', 'Q4']
}]
},
options: {
scales: {
x: {
display: 'auto'
},
y: {
type: 'category',
}
}
}
});
var scale = chart.scales.x;
scale.ctx = window.createMockContext();
chart.draw();
expect(scale.ctx.getCalls().length).toBeGreaterThan(0);
expect(scale.height).toBeGreaterThan(0);
});
it('should not draw the axes if no associated datasets are visible', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [100, 200, 100, 50],
xAxisId: 'foo',
hidden: true,
labels: ['Q1', 'Q2', 'Q3', 'Q4']
}]
},
options: {
scales: {
x: {
display: 'auto'
}
}
}
});
var scale = chart.scales.x;
scale.ctx = window.createMockContext();
chart.draw();
expect(scale.ctx.getCalls().length).toBe(0);
expect(scale.height).toBe(0);
});
});
describe('for the y axes', function() {
it('should draw the axes if at least one associated dataset is visible', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [100, 200, 100, 50],
yAxisId: 'foo',
hidden: true,
labels: ['Q1', 'Q2', 'Q3', 'Q4']
}, {
data: [100, 200, 100, 50],
yAxisId: 'foo',
labels: ['Q1', 'Q2', 'Q3', 'Q4']
}]
},
options: {
scales: {
y: {
display: 'auto'
}
}
}
});
var scale = chart.scales.y;
scale.ctx = window.createMockContext();
chart.draw();
expect(scale.ctx.getCalls().length).toBeGreaterThan(0);
expect(scale.width).toBeGreaterThan(0);
});
it('should not draw the axes if no associated datasets are visible', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [100, 200, 100, 50],
yAxisId: 'foo',
hidden: true,
labels: ['Q1', 'Q2', 'Q3', 'Q4']
}]
},
options: {
scales: {
y: {
display: 'auto'
}
}
}
});
var scale = chart.scales.y;
scale.ctx = window.createMockContext();
chart.draw();
expect(scale.ctx.getCalls().length).toBe(0);
expect(scale.width).toBe(0);
});
});
});
describe('afterBuildTicks', function() {
it('should allow filtering of ticks', function() {
var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'];
var chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'category',
labels: labels,
afterBuildTicks: function(scale) {
scale.ticks = scale.ticks.slice(1);
}
}
}
}
});
var scale = chart.scales.x;
expect(getLabels(scale)).toEqual(labels.slice(1));
});
it('should allow no return value from callback', function() {
var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'];
var chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'category',
labels: labels,
afterBuildTicks: function() { }
}
}
}
});
var scale = chart.scales.x;
expect(getLabels(scale)).toEqual(labels);
});
it('should allow empty ticks', function() {
var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'];
var chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'category',
labels: labels,
afterBuildTicks: function(scale) {
scale.ticks = [];
}
}
}
}
});
var scale = chart.scales.x;
expect(scale.ticks.length).toBe(0);
});
});
describe('_layers', function() {
it('should default to three layers', function() {
var chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'linear',
}
}
}
});
var scale = chart.scales.x;
expect(scale._layers().length).toEqual(3);
});
it('should create the chart with custom scale ids without axis or position options', function() {
function createChart() {
return window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 2}],
xAxisID: 'customIDx',
yAxisID: 'customIDy'
}]
},
options: {
scales: {
customIDx: {
type: 'linear',
display: false
},
customIDy: {
type: 'linear',
display: false
}
}
}
});
}
expect(createChart).not.toThrow();
});
it('should default to one layer for custom scales', function() {
class CustomScale extends Chart.Scale {
draw() {}
convertTicksToLabels() {
return ['tick'];
}
}
CustomScale.id = 'customScale';
CustomScale.defaults = {};
Chart.register(CustomScale);
var chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'customScale',
grid: {
z: 10
},
ticks: {
z: 20
}
}
}
}
});
var scale = chart.scales.x;
expect(scale._layers().length).toEqual(1);
expect(scale._layers()[0].z).toEqual(20);
});
it('should default to one layer for custom scales for axis', function() {
class CustomScale1 extends Chart.Scale {
draw() {}
convertTicksToLabels() {
return ['tick'];
}
}
CustomScale1.id = 'customScale1';
CustomScale1.defaults = {axis: 'x'};
Chart.register(CustomScale1);
var chart = window.acquireChart({
type: 'line',
options: {
scales: {
my: {
type: 'customScale1',
grid: {
z: 10
},
ticks: {
z: 20
}
}
}
}
});
var scale = chart.scales.my;
expect(scale._layers().length).toEqual(1);
expect(scale._layers()[0].z).toEqual(20);
});
it('should fail for custom scales without any axis or position', function() {
class CustomScale2 extends Chart.Scale {
draw() {}
}
CustomScale2.id = 'customScale2';
CustomScale2.defaults = {};
Chart.register(CustomScale2);
function createChart() {
return window.acquireChart({
type: 'line',
options: {
scales: {
my: {
type: 'customScale2'
}
}
}
});
}
expect(createChart).toThrow(new Error('Cannot determine type of \'my\' axis. Please provide \'axis\' or \'position\' option.'));
});
it('should return 3 layers when z is not equal between ticks and grid', function() {
var chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'linear',
ticks: {
z: 10
}
}
}
}
});
expect(chart.scales.x._layers().length).toEqual(3);
chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'linear',
grid: {
z: 11
}
}
}
}
});
expect(chart.scales.x._layers().length).toEqual(3);
chart = window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'linear',
ticks: {
z: 10
},
grid: {
z: 11
}
}
}
}
});
expect(chart.scales.x._layers().length).toEqual(3);
});
});
describe('min and max', function() {
it('should be limited to visible data', function() {
var chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{x: 100, y: 100}, {x: -100, y: -100}]
}, {
data: [{x: 10, y: 10}, {x: -10, y: -10}]
}]
},
options: {
scales: {
x: {
id: 'x',
type: 'linear',
min: -20,
max: 20
},
y: {
id: 'y',
type: 'linear'
}
}
}
});
expect(chart.scales.x.min).toEqual(-20);
expect(chart.scales.x.max).toEqual(20);
expect(chart.scales.y.min).toEqual(-10);
expect(chart.scales.y.max).toEqual(10);
});
});
describe('overrides', () => {
it('should create new scale', () => {
const chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{x: 100, y: 100}, {x: -100, y: -100}]
}, {
data: [{x: 10, y: 10}, {x: -10, y: -10}]
}]
},
options: {
scales: {
x2: {
type: 'linear',
min: -20,
max: 20
}
}
}
});
expect(Object.keys(chart.scales).sort()).toEqual(['x', 'x2', 'y']);
});
it('should create new scale with custom name', () => {
const chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{x: 100, y: 100}, {x: -100, y: -100}]
}, {
data: [{x: 10, y: 10}, {x: -10, y: -10}]
}]
},
options: {
scales: {
scaleX: {
axis: 'x',
type: 'linear',
min: -20,
max: 20
}
}
}
});
expect(Object.keys(chart.scales).sort()).toEqual(['scaleX', 'x', 'y']);
});
it('should throw error on scale with custom name without axis type', () => {
expect(() => window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{x: 100, y: 100}, {x: -100, y: -100}]
}, {
data: [{x: 10, y: 10}, {x: -10, y: -10}]
}]
},
options: {
scales: {
scaleX: {
type: 'linear',
min: -20,
max: 20
}
}
}
})).toThrow();
});
it('should read options first to determine axis', () => {
const chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{x: 100, y: 100}, {x: -100, y: -100}]
}, {
data: [{x: 10, y: 10}, {x: -10, y: -10}]
}]
},
options: {
scales: {
xavier: {
axis: 'y',
type: 'linear',
min: -20,
max: 20
}
}
}
});
expect(chart.scales.xavier.axis).toBe('y');
});
it('should center labels when rotated in x axis', () => {
const chart = window.acquireChart({
type: 'line',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3]
}]
},
options: {
scales: {
x: {
ticks: {
minRotation: 90,
}
}
}
}
});
const mapper = item => parseFloat(item.options.translation[0].toFixed(2));
const expected = [20.15, 113.6, 207.05, 300.5, 393.95, 487.4];
const actual = chart.scales.x.getLabelItems().map(mapper);
const len = expected.length;
for (let i = 0; i < len; ++i) {
const actualValue = actual[i];
const expectedValue = expected[i];
expect(actualValue).toBeCloseTo(expectedValue, 1);
}
});
});
describe('Scale Title stroke', ()=>{
function getChartWithScaleTitleStroke() {
return window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'linear',
title: {
display: true,
text: 'title-x',
color: '#ddd',
strokeWidth: 1,
strokeColor: '#333'
}
},
y: {
type: 'linear',
title: {
display: true,
text: 'title-y',
color: '#ddd',
strokeWidth: 2,
strokeColor: '#222'
}
}
}
}
});
}
function getChartWithoutScaleTitleStroke() {
return window.acquireChart({
type: 'line',
options: {
scales: {
x: {
type: 'linear',
title: {
display: true,
text: 'title-x',
color: '#ddd'
}
},
y: {
type: 'linear',
title: {
display: true,
text: 'title-y',
color: '#ddd'
}
}
}
}
});
}
it('should draw a scale title stroke when provided x-axis', function() {
var chart = getChartWithScaleTitleStroke();
var scale = chart.scales.x;
expect(scale.options.title.strokeColor).toEqual('#333');
expect(scale.options.title.strokeWidth).toEqual(1);
});
it('should draw a scale title stroke when provided y-axis', function() {
var chart = getChartWithScaleTitleStroke();
var scale = chart.scales.y;
expect(scale.options.title.strokeColor).toEqual('#222');
expect(scale.options.title.strokeWidth).toEqual(2);
});
it('should not draw a scale title stroke when not provided', function() {
var chart = getChartWithoutScaleTitleStroke();
var scales = chart.scales;
expect(scales.y.options.title.strokeColor).toBeUndefined();
expect(scales.y.options.title.strokeWidth).toBeUndefined();
expect(scales.x.options.title.strokeColor).toBeUndefined();
expect(scales.x.options.title.strokeWidth).toBeUndefined();
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/element.point.tests.js | test/specs/element.point.tests.js | describe('Chart.elements.PointElement', function() {
describe('auto', jasmine.fixture.specs('element.point'));
it ('Should correctly identify as in range', function() {
// Mock out the point as if we were made by the controller
var point = new Chart.elements.PointElement({
options: {
radius: 2,
hitRadius: 3,
},
x: 10,
y: 15
});
expect(point.inRange(10, 15)).toBe(true);
expect(point.inRange(10, 10)).toBe(false);
expect(point.inRange(10, 5)).toBe(false);
expect(point.inRange(5, 5)).toBe(false);
});
it ('should get the correct tooltip position', function() {
// Mock out the point as if we were made by the controller
var point = new Chart.elements.PointElement({
options: {
radius: 2,
borderWidth: 6,
},
x: 10,
y: 15
});
expect(point.tooltipPosition()).toEqual({
x: 10,
y: 15
});
});
it('should get the correct center point', function() {
// Mock out the point as if we were made by the controller
var point = new Chart.elements.PointElement({
options: {
radius: 2,
},
x: 10,
y: 10
});
expect(point.getCenterPoint()).toEqual({x: 10, y: 10});
});
it ('should not draw if skipped', function() {
var mockContext = window.createMockContext();
// Mock out the point as if we were made by the controller
var point = new Chart.elements.PointElement({
options: {
radius: 2,
hitRadius: 3,
},
x: 10,
y: 15,
skip: true
});
point.draw(mockContext);
expect(mockContext.getCalls()).toEqual([]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.animations.tests.js | test/specs/core.animations.tests.js | describe('Chart.animations', function() {
it('should override property collection with property', function() {
const chart = {};
const anims = new Chart.Animations(chart, {
collection1: {
properties: ['property1', 'property2'],
duration: 1000
},
property2: {
duration: 2000
}
});
expect(anims._properties.get('property1')).toEqual(jasmine.objectContaining({duration: 1000}));
expect(anims._properties.get('property2')).toEqual(jasmine.objectContaining({duration: 2000}));
});
it('should ignore duplicate definitions from collections', function() {
const chart = {};
const anims = new Chart.Animations(chart, {
collection1: {
properties: ['property1'],
duration: 1000
},
collection2: {
properties: ['property1', 'property2'],
duration: 2000
}
});
expect(anims._properties.get('property1')).toEqual(jasmine.objectContaining({duration: 1000}));
expect(anims._properties.get('property2')).toEqual(jasmine.objectContaining({duration: 2000}));
});
it('should not animate undefined options key', function() {
const chart = {};
const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
const target = {
value: 1,
options: {
option: 2
}
};
expect(anims.update(target, {
options: undefined
})).toBeUndefined();
});
it('should assign options directly, if target does not have previous options', function() {
const chart = {};
const anims = new Chart.Animations(chart, {option: {duration: 200}});
const target = {};
expect(anims.update(target, {options: {option: 1}})).toBeUndefined();
});
it('should clone the target options, if those are shared and new options are not', function() {
const chart = {options: {}};
const anims = new Chart.Animations(chart, {option: {duration: 200}});
const options = {option: 0, $shared: true};
const target = {options};
expect(anims.update(target, {options: {option: 1}})).toBeTrue();
expect(target.options.$shared).not.toBeTrue();
expect(target.options !== options).toBeTrue();
});
it('should assign shared options to target after animations complete', function(done) {
const chart = {
draw: function() {},
options: {}
};
const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
const target = {
value: 1,
options: {
option: 2
}
};
const sharedOpts = {option: 10, $shared: true};
expect(anims.update(target, {
options: sharedOpts
})).toBeTrue();
expect(target.options !== sharedOpts).toBeTrue();
Chart.animator.start(chart);
setTimeout(function() {
expect(Chart.animator.running(chart)).toBeFalse();
expect(target.options === sharedOpts).toBeTrue();
Chart.animator.remove(chart);
done();
}, 300);
});
it('should not assign shared options to target when animations are cancelled', function(done) {
const chart = {
draw: function() {},
options: {}
};
const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
const target = {
value: 1,
options: {
option: 2
}
};
const sharedOpts = {option: 10, $shared: true};
expect(anims.update(target, {
options: sharedOpts
})).toBeTrue();
expect(target.options !== sharedOpts).toBeTrue();
Chart.animator.start(chart);
setTimeout(function() {
expect(Chart.animator.running(chart)).toBeTrue();
Chart.animator.stop(chart);
expect(Chart.animator.running(chart)).toBeFalse();
setTimeout(function() {
expect(target.options === sharedOpts).toBeFalse();
Chart.animator.remove(chart);
done();
}, 250);
}, 50);
});
it('should assign final shared options to target after animations complete', function(done) {
const chart = {
draw: function() {},
options: {}
};
const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}});
const origOpts = {option: 2};
const target = {
value: 1,
options: origOpts
};
const sharedOpts = {option: 10, $shared: true};
const sharedOpts2 = {option: 20, $shared: true};
expect(anims.update(target, {
options: sharedOpts
})).toBeTrue();
expect(target.options !== sharedOpts).toBeTrue();
Chart.animator.start(chart);
setTimeout(function() {
expect(Chart.animator.running(chart)).toBeTrue();
expect(target.options === origOpts).toBeTrue();
expect(anims.update(target, {
options: sharedOpts2
})).toBeUndefined();
expect(target.options === origOpts).toBeTrue();
setTimeout(function() {
expect(target.options === sharedOpts2).toBeTrue();
Chart.animator.remove(chart);
done();
}, 250);
}, 50);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/mixed.tests.js | test/specs/mixed.tests.js | describe('Mixed charts', function() {
describe('auto', jasmine.fixture.specs('mixed'));
it('shoud be constructed with doughnuts chart', function() {
const chart = window.acquireChart({
data: {
datasets: [{
type: 'line',
data: [10, 20, 30, 40],
}, {
type: 'doughnut',
data: [10, 20, 30, 50],
}
],
labels: []
}
});
const meta0 = chart.getDatasetMeta(0);
expect(meta0.type).toEqual('line');
const meta1 = chart.getDatasetMeta(1);
expect(meta1.type).toEqual('doughnut');
});
it('shoud be constructed with pie chart', function() {
const chart = window.acquireChart({
data: {
datasets: [{
type: 'bar',
data: [10, 20, 30, 40],
}, {
type: 'pie',
data: [10, 20, 30, 50],
}
],
labels: []
}
});
const meta0 = chart.getDatasetMeta(0);
expect(meta0.type).toEqual('bar');
const meta1 = chart.getDatasetMeta(1);
expect(meta1.type).toEqual('pie');
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.datasetController.tests.js | test/specs/core.datasetController.tests.js | describe('Chart.DatasetController', function() {
describe('auto', jasmine.fixture.specs('core.datasetController'));
it('should listen for dataset data insertions or removals', function() {
var data = [0, 1, 2, 3, 4, 5];
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data
}]
}
});
var controller = chart.getDatasetMeta(0).controller;
var methods = [
'_onDataPush',
'_onDataPop',
'_onDataShift',
'_onDataSplice',
'_onDataUnshift'
];
methods.forEach(function(method) {
spyOn(controller, method);
});
data.push(6, 7, 8);
data.push(9);
data.pop();
data.shift();
data.shift();
data.shift();
data.splice(1, 4, 10, 11);
data.unshift(12, 13, 14, 15);
data.unshift(16, 17);
[2, 1, 3, 1, 2].forEach(function(expected, index) {
expect(controller[methods[index]].calls.count()).toBe(expected);
});
});
it('should not try to delete non existent stacks', function() {
function createAndUpdateChart() {
var chart = acquireChart({
data: {
labels: ['q'],
datasets: [
{
id: 'dismissed',
label: 'Test before',
yAxisID: 'count',
data: [816],
type: 'bar',
stack: 'stack'
}
]
},
options: {
scales: {
count: {
axis: 'y',
type: 'linear'
}
}
}
});
chart.data = {
datasets: [
{
id: 'tests',
yAxisID: 'count',
label: 'Test after',
data: [38300],
type: 'bar'
}
],
labels: ['q']
};
chart.update();
}
expect(createAndUpdateChart).not.toThrow();
});
describe('inextensible data', function() {
it('should handle a frozen data object', function() {
function createChart() {
var data = Object.freeze([0, 1, 2, 3, 4, 5]);
expect(Object.isExtensible(data)).toBeFalsy();
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data
}]
}
});
var dataset = chart.data.datasets[0];
dataset.data = Object.freeze([5, 4, 3, 2, 1, 0]);
expect(Object.isExtensible(dataset.data)).toBeFalsy();
chart.update();
// Tests that the unlisten path also works for frozen objects
chart.destroy();
}
expect(createChart).not.toThrow();
});
it('should handle a sealed data object', function() {
function createChart() {
var data = Object.seal([0, 1, 2, 3, 4, 5]);
expect(Object.isExtensible(data)).toBeFalsy();
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data
}]
}
});
var dataset = chart.data.datasets[0];
dataset.data = Object.seal([5, 4, 3, 2, 1, 0]);
expect(Object.isExtensible(dataset.data)).toBeFalsy();
chart.update();
// Tests that the unlisten path also works for frozen objects
chart.destroy();
}
expect(createChart).not.toThrow();
});
it('should handle an unextendable data object', function() {
function createChart() {
var data = Object.preventExtensions([0, 1, 2, 3, 4, 5]);
expect(Object.isExtensible(data)).toBeFalsy();
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data
}]
}
});
var dataset = chart.data.datasets[0];
dataset.data = Object.preventExtensions([5, 4, 3, 2, 1, 0]);
expect(Object.isExtensible(dataset.data)).toBeFalsy();
chart.update();
// Tests that the unlisten path also works for frozen objects
chart.destroy();
}
expect(createChart).not.toThrow();
});
});
it('should parse data using correct scales', function() {
const data1 = [0, 1, 2, 3, 4, 5];
const data2 = ['a', 'b', 'c', 'd', 'a'];
const chart = acquireChart({
type: 'line',
data: {
datasets: [
{data: data1},
{data: data2, xAxisID: 'x2', yAxisID: 'y2'}
]
},
options: {
scales: {
x: {
type: 'category',
labels: ['one', 'two', 'three', 'four', 'five', 'six']
},
x2: {
type: 'logarithmic',
labels: ['1', '10', '100', '1000', '2000']
},
y: {
type: 'linear'
},
y2: {
type: 'category',
labels: ['a', 'b', 'c', 'd', 'e']
}
}
}
});
const meta1 = chart.getDatasetMeta(0);
const parsedXValues1 = meta1._parsed.map(p => p.x);
const parsedYValues1 = meta1._parsed.map(p => p.y);
expect(meta1.data.length).toBe(6);
expect(parsedXValues1).toEqual([0, 1, 2, 3, 4, 5]); // label indices
expect(parsedYValues1).toEqual(data1);
const meta2 = chart.getDatasetMeta(1);
const parsedXValues2 = meta2._parsed.map(p => p.x);
const parsedYValues2 = meta2._parsed.map(p => p.y);
expect(meta2.data.length).toBe(5);
expect(parsedXValues2).toEqual([1, 10, 100, 1000, 2000]); // logarithmic scale labels
expect(parsedYValues2).toEqual([0, 1, 2, 3, 0]); // label indices
});
it('should parse using provided keys', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [
{x: 1, data: {key: 'one', value: 20}},
{data: {key: 'two', value: 30}}
]
}]
},
options: {
parsing: {
xAxisKey: 'data.key',
yAxisKey: 'data.value'
},
scales: {
x: {
type: 'category',
labels: ['one', 'two']
},
y: {
type: 'linear'
},
}
}
});
const meta = chart.getDatasetMeta(0);
const parsedXValues = meta._parsed.map(p => p.x);
const parsedYValues = meta._parsed.map(p => p.y);
expect(meta.data.length).toBe(2);
expect(parsedXValues).toEqual([0, 1]); // label indices
expect(parsedYValues).toEqual([20, 30]);
});
describe('labels array synchronization', function() {
const data1 = [
{x: 'One', name: 'One', y: 1, value: 1},
{x: 'Two', name: 'Two', y: 2, value: 2}
];
const data2 = [
{x: 'Three', name: 'Three', y: 3, value: 3},
{x: 'Four', name: 'Four', y: 4, value: 4},
{x: 'Five', name: 'Five', y: 5, value: 5}
];
[
true,
false,
{
xAxisKey: 'name',
yAxisKey: 'value'
}
].forEach(function(parsing) {
describe('when parsing is ' + JSON.stringify(parsing), function() {
it('should remove old labels when data is updated', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data1
}]
},
options: {
parsing
}
});
chart.data.datasets[0].data = data2;
chart.update();
const meta = chart.getDatasetMeta(0);
const labels = meta.iScale.getLabels();
expect(labels).toEqual(data2.map(n => n.x));
});
it('should not remove any user added labels', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data1
}]
},
options: {
parsing
}
});
chart.data.labels.push('user-added');
chart.data.datasets[0].data = [];
chart.update();
const meta = chart.getDatasetMeta(0);
const labels = meta.iScale.getLabels();
expect(labels).toEqual(['user-added']);
});
it('should not remove any user defined labels', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data1
}],
labels: ['user1', 'user2']
},
options: {
parsing
}
});
const meta = chart.getDatasetMeta(0);
expect(meta.iScale.getLabels()).toEqual(['user1', 'user2'].concat(data1.map(n => n.x)));
chart.data.datasets[0].data = data2;
chart.update();
expect(meta.iScale.getLabels()).toEqual(['user1', 'user2'].concat(data2.map(n => n.x)));
});
it('should keep up with multiple datasets', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data1
}, {
data: data2
}],
labels: ['One', 'Three']
},
options: {
parsing
}
});
const scale = chart.scales.x;
expect(scale.getLabels()).toEqual(['One', 'Three', 'Two', 'Four', 'Five']);
chart.data.datasets[0].data = data2;
chart.data.datasets[1].data = data1;
chart.update();
expect(scale.getLabels()).toEqual(['One', 'Three', 'Four', 'Five', 'Two']);
});
});
});
});
it('should synchronize metadata when data are inserted or removed and parsing is on', function() {
const data = [0, 1, 2, 3, 4, 5];
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data
}]
}
});
const meta = chart.getDatasetMeta(0);
const parsedYValues = () => meta._parsed.map(p => p.y);
let first, second, last;
first = meta.data[0];
last = meta.data[5];
data.push(6, 7, 8);
data.push(9);
chart.update();
expect(meta.data.length).toBe(10);
expect(meta.data[0]).toBe(first);
expect(meta.data[5]).toBe(last);
expect(parsedYValues()).toEqual(data);
last = meta.data[9];
data.pop();
chart.update();
expect(meta.data.length).toBe(9);
expect(meta.data[0]).toBe(first);
expect(meta.data.indexOf(last)).toBe(-1);
expect(parsedYValues()).toEqual(data);
last = meta.data[8];
data.shift();
data.shift();
data.shift();
chart.update();
expect(meta.data.length).toBe(6);
expect(meta.data.indexOf(first)).toBe(-1);
expect(meta.data[5]).toBe(last);
expect(parsedYValues()).toEqual(data);
first = meta.data[0];
second = meta.data[1];
last = meta.data[5];
data.splice(1, 4, 10, 11);
chart.update();
expect(meta.data.length).toBe(4);
expect(meta.data[0]).toBe(first);
expect(meta.data[3]).toBe(last);
expect(meta.data.indexOf(second)).toBe(-1);
expect(parsedYValues()).toEqual(data);
data.unshift(12, 13, 14, 15);
data.unshift(16, 17);
chart.update();
expect(meta.data.length).toBe(10);
expect(meta.data[6]).toBe(first);
expect(meta.data[9]).toBe(last);
expect(parsedYValues()).toEqual(data);
});
it('should synchronize metadata when data are inserted or removed and parsing is off', function() {
var data = [{x: 0, y: 0}, {x: 1, y: 1}, {x: 2, y: 2}, {x: 3, y: 3}, {x: 4, y: 4}, {x: 5, y: 5}];
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data
}]
},
options: {
parsing: false,
scales: {
x: {type: 'linear'},
y: {type: 'linear'}
}
}
});
var meta = chart.getDatasetMeta(0);
var controller = meta.controller;
var first, last;
first = controller.getParsed(0);
last = controller.getParsed(5);
data.push({x: 6, y: 6}, {x: 7, y: 7}, {x: 8, y: 8});
data.push({x: 9, y: 9});
chart.update();
expect(meta.data.length).toBe(10);
expect(controller.getParsed(0)).toBe(first);
expect(controller.getParsed(5)).toBe(last);
last = controller.getParsed(9);
data.pop();
chart.update();
expect(meta.data.length).toBe(9);
expect(controller.getParsed(0)).toBe(first);
expect(controller.getParsed(9)).toBe(undefined);
expect(controller.getParsed(8)).toEqual({x: 8, y: 8});
last = controller.getParsed(8);
data.shift();
data.shift();
data.shift();
chart.update();
expect(meta.data.length).toBe(6);
expect(controller.getParsed(5)).toBe(last);
first = controller.getParsed(0);
last = controller.getParsed(5);
data.splice(1, 4, {x: 10, y: 10}, {x: 11, y: 11});
chart.update();
expect(meta.data.length).toBe(4);
expect(controller.getParsed(0)).toBe(first);
expect(controller.getParsed(3)).toBe(last);
expect(controller.getParsed(1)).toEqual({x: 10, y: 10});
data.unshift({x: 12, y: 12}, {x: 13, y: 13}, {x: 14, y: 14}, {x: 15, y: 15});
data.unshift({x: 16, y: 16}, {x: 17, y: 17});
chart.update();
expect(meta.data.length).toBe(10);
expect(controller.getParsed(6)).toBe(first);
expect(controller.getParsed(9)).toBe(last);
});
it('should synchronize insert before removal when parsing is off', function() {
// https://github.com/chartjs/Chart.js/issues/9511
const data = [{x: 0, y: 1}, {x: 2, y: 7}, {x: 3, y: 5}];
var chart = acquireChart({
type: 'scatter',
data: {
datasets: [{
data: data,
}],
},
options: {
parsing: false,
scales: {
x: {
type: 'linear',
min: 0,
max: 10,
},
y: {
type: 'linear',
min: 0,
max: 10,
},
},
},
});
var meta = chart.getDatasetMeta(0);
var controller = meta.controller;
data.push({
x: 10,
y: 6
});
data.splice(0, 1);
chart.update();
expect(meta.data.length).toBe(3);
expect(controller.getParsed(0)).toBe(data[0]);
expect(controller.getParsed(2)).toBe(data[2]);
});
it('should re-synchronize metadata when the data object reference changes', function() {
var data0 = [0, 1, 2, 3, 4, 5];
var data1 = [6, 7, 8];
var data2 = [1, 2, 3, 4, 5, 6, 7, 8];
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data0
}]
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(6);
expect(meta._parsed.map(p => p.y)).toEqual(data0);
const point0 = meta.data[0];
chart.data.datasets[0].data = data1;
chart.update();
expect(meta.data.length).toBe(3);
expect(meta._parsed.map(p => p.y)).toEqual(data1);
expect(meta.data[0]).toEqual(point0);
data1.push(9);
chart.update();
expect(meta.data.length).toBe(4);
chart.data.datasets[0].data = data0;
chart.update();
expect(meta.data.length).toBe(6);
expect(meta._parsed.map(p => p.y)).toEqual(data0);
chart.data.datasets[0].data = data2;
chart.update();
expect(meta.data.length).toBe(8);
expect(meta._parsed.map(p => p.y)).toEqual(data2);
});
it('should re-synchronize metadata when the data object reference changes, with animation', function() {
var data0 = [0, 1, 2, 3, 4, 5];
var data1 = [6, 7, 8];
var data2 = [1, 2, 3, 4, 5, 6, 7, 8];
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data0
}]
},
options: {
animation: true
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(6);
expect(meta._parsed.map(p => p.y)).toEqual(data0);
const point0 = meta.data[0];
chart.data.datasets[0].data = data1;
chart.update();
expect(meta.data.length).toBe(3);
expect(meta._parsed.map(p => p.y)).toEqual(data1);
expect(meta.data[0]).toEqual(point0);
data1.push(9);
chart.update();
expect(meta.data.length).toBe(4);
chart.data.datasets[0].data = data0;
chart.update();
expect(meta.data.length).toBe(6);
expect(meta._parsed.map(p => p.y)).toEqual(data0);
chart.data.datasets[0].data = data2;
chart.update();
expect(meta.data.length).toBe(8);
expect(meta._parsed.map(p => p.y)).toEqual(data2);
});
it('should re-synchronize metadata when data are unusually altered', function() {
var data = [0, 1, 2, 3, 4, 5];
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data
}]
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(6);
data.length = 2;
chart.update();
expect(meta.data.length).toBe(2);
data.length = 42;
chart.update();
expect(meta.data.length).toBe(42);
});
// https://github.com/chartjs/Chart.js/issues/7243
it('should re-synchronize metadata when data is moved and values are equal', function() {
var data = [10, 10, 10, 10, 10, 10];
var chart = acquireChart({
type: 'line',
data: {
labels: ['a', 'b', 'c', 'd', 'e', 'f'],
datasets: [{
data,
fill: true
}]
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(6);
const firstX = meta.data[0].x;
data.push(data.shift());
chart.update();
expect(meta.data.length).toBe(6);
expect(meta.data[0].x).toEqual(firstX);
});
// https://github.com/chartjs/Chart.js/issues/7445
it('should re-synchronize metadata when data is objects and directly altered', function() {
var data = [{x: 'a', y: 1}, {x: 'b', y: 2}, {x: 'c', y: 3}];
var chart = acquireChart({
type: 'line',
data: {
labels: ['a', 'b', 'c'],
datasets: [{
data,
fill: true
}]
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(3);
const y3 = meta.data[2].y;
data[0].y = 3;
chart.update();
expect(meta.data[0].y).toEqual(y3);
});
it('should re-synchronize metadata when scaleID changes', function() {
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [],
xAxisID: 'firstXScaleID',
yAxisID: 'firstYScaleID',
}]
},
options: {
scales: {
firstXScaleID: {
type: 'category',
position: 'bottom'
},
secondXScaleID: {
type: 'category',
position: 'bottom'
},
firstYScaleID: {
type: 'linear',
position: 'left'
},
secondYScaleID: {
type: 'linear',
position: 'left'
},
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.xAxisID).toBe('firstXScaleID');
expect(meta.yAxisID).toBe('firstYScaleID');
chart.data.datasets[0].xAxisID = 'secondXScaleID';
chart.data.datasets[0].yAxisID = 'secondYScaleID';
chart.update();
expect(meta.xAxisID).toBe('secondXScaleID');
expect(meta.yAxisID).toBe('secondYScaleID');
});
it('should re-synchronize stacks when stack is changed', function() {
var chart = acquireChart({
type: 'bar',
data: {
labels: ['a', 'b'],
datasets: [{
data: [1, 10],
stack: '1'
}, {
data: [2, 20],
stack: '2'
}, {
data: [3, 30],
stack: '1'
}]
}
});
expect(chart._stacks).toEqual({
'x.y.1': {
0: {0: 1, 2: 3, _top: 2, _bottom: null, _visualValues: {0: 1, 2: 3}},
1: {0: 10, 2: 30, _top: 2, _bottom: null, _visualValues: {0: 10, 2: 30}}
},
'x.y.2': {
0: {1: 2, _top: 1, _bottom: null, _visualValues: {1: 2}},
1: {1: 20, _top: 1, _bottom: null, _visualValues: {1: 20}}
}
});
chart.data.datasets[2].stack = '2';
chart.update();
expect(chart._stacks).toEqual({
'x.y.1': {
0: {0: 1, _top: 2, _bottom: null, _visualValues: {0: 1}},
1: {0: 10, _top: 2, _bottom: null, _visualValues: {0: 10}}
},
'x.y.2': {
0: {1: 2, 2: 3, _top: 2, _bottom: null, _visualValues: {1: 2, 2: 3}},
1: {1: 20, 2: 30, _top: 2, _bottom: null, _visualValues: {1: 20, 2: 30}}
}
});
});
it('should re-synchronize stacks when data is removed', function() {
var chart = acquireChart({
type: 'bar',
data: {
labels: ['a', 'b'],
datasets: [{
data: [1, 10],
stack: '1'
}, {
data: [2, 20],
stack: '2'
}, {
data: [3, 30],
stack: '1'
}]
}
});
expect(chart._stacks).toEqual({
'x.y.1': {
0: {0: 1, 2: 3, _top: 2, _bottom: null, _visualValues: {0: 1, 2: 3}},
1: {0: 10, 2: 30, _top: 2, _bottom: null, _visualValues: {0: 10, 2: 30}}
},
'x.y.2': {
0: {1: 2, _top: 1, _bottom: null, _visualValues: {1: 2}},
1: {1: 20, _top: 1, _bottom: null, _visualValues: {1: 20}}
}
});
chart.data.datasets[2].data = [4];
chart.update();
expect(chart._stacks).toEqual({
'x.y.1': {
0: {0: 1, 2: 4, _top: 2, _bottom: null, _visualValues: {0: 1, 2: 4}},
1: {0: 10, _top: 2, _bottom: null, _visualValues: {0: 10}}
},
'x.y.2': {
0: {1: 2, _top: 1, _bottom: null, _visualValues: {1: 2}},
1: {1: 20, _top: 1, _bottom: null, _visualValues: {1: 20}}
}
});
});
it('should cleanup attached properties when the reference changes or when the chart is destroyed', function() {
var data0 = [0, 1, 2, 3, 4, 5];
var data1 = [6, 7, 8];
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data0
}]
}
});
var hooks = ['push', 'pop', 'shift', 'splice', 'unshift'];
expect(data0._chartjs).toBeDefined();
hooks.forEach(function(hook) {
expect(data0[hook]).not.toBe(Array.prototype[hook]);
});
expect(data1._chartjs).not.toBeDefined();
hooks.forEach(function(hook) {
expect(data1[hook]).toBe(Array.prototype[hook]);
});
chart.data.datasets[0].data = data1;
chart.update();
expect(data0._chartjs).not.toBeDefined();
hooks.forEach(function(hook) {
expect(data0[hook]).toBe(Array.prototype[hook]);
});
expect(data1._chartjs).toBeDefined();
hooks.forEach(function(hook) {
expect(data1[hook]).not.toBe(Array.prototype[hook]);
});
chart.destroy();
expect(data1._chartjs).not.toBeDefined();
hooks.forEach(function(hook) {
expect(data1[hook]).toBe(Array.prototype[hook]);
});
});
it('should resolve data element options to the default color', function() {
var data0 = [0, 1, 2, 3, 4, 5];
var oldColor = Chart.defaults.borderColor;
Chart.defaults.borderColor = 'red';
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: data0
}]
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.dataset.options.borderColor).toBe('red');
expect(meta.data[0].options.borderColor).toBe('red');
// Reset old shared state
Chart.defaults.borderColor = oldColor;
});
it('should read parsing from options when default is false', function() {
const originalDefault = Chart.defaults.parsing;
Chart.defaults.parsing = false;
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [{t: 1, y: 0}]
}]
},
options: {
parsing: {
xAxisKey: 't'
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data[0].x).not.toBeNaN();
// Reset old shared state
Chart.defaults.parsing = originalDefault;
});
it('should not fail to produce stacks when parsing is off', function() {
var chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [{x: 1, y: 10}]
}, {
data: [{x: 1, y: 20}]
}]
},
options: {
parsing: false,
scales: {
x: {stacked: true},
y: {stacked: true}
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta._parsed[0]._stacks).toEqual(jasmine.objectContaining({y: {0: 10, 1: 20, _top: 1, _bottom: null, _visualValues: {0: 10, 1: 20}}}));
});
describe('resolveDataElementOptions', function() {
it('should cache options when possible', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [1, 2, 3],
}]
},
});
const controller = chart.getDatasetMeta(0).controller;
expect(controller.enableOptionSharing).toBeTrue();
const opts0 = controller.resolveDataElementOptions(0);
const opts1 = controller.resolveDataElementOptions(1);
expect(opts0 === opts1).toBeTrue();
expect(opts0.$shared).toBeTrue();
expect(Object.isFrozen(opts0)).toBeTrue();
});
it('should not cache options when option sharing is disabled', function() {
const chart = acquireChart({
type: 'radar',
data: {
datasets: [{
data: [1, 2, 3],
}]
},
});
const controller = chart.getDatasetMeta(0).controller;
expect(controller.enableOptionSharing).toBeFalse();
const opts0 = controller.resolveDataElementOptions(0);
const opts1 = controller.resolveDataElementOptions(1);
expect(opts0 === opts1).toBeFalse();
expect(opts0.$shared).not.toBeTrue();
expect(Object.isFrozen(opts0)).toBeFalse();
});
it('should not cache options when functions are used', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [1, 2, 3],
backgroundColor: () => 'red'
}]
},
});
const controller = chart.getDatasetMeta(0).controller;
const opts0 = controller.resolveDataElementOptions(0);
const opts1 = controller.resolveDataElementOptions(1);
expect(opts0 === opts1).toBeFalse();
expect(opts0.$shared).not.toBeTrue();
expect(Object.isFrozen(opts0)).toBeFalse();
});
it('should support nested scriptable options', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [100, 120, 130],
fill: {
value: (ctx) => ctx.type === 'dataset' ? 75 : 0
}
}]
},
});
const controller = chart.getDatasetMeta(0).controller;
const opts = controller.resolveDatasetElementOptions();
expect(opts).toEqualOptions({
fill: {
value: 75
}
});
});
it('should support nested scriptable defaults', function() {
Chart.defaults.datasets.line.fill = {
value: (ctx) => ctx.type === 'dataset' ? 75 : 0
};
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [100, 120, 130],
}]
},
});
const controller = chart.getDatasetMeta(0).controller;
const opts = controller.resolveDatasetElementOptions();
expect(opts).toEqualOptions({
fill: {
value: 75
}
});
delete Chart.defaults.datasets.line.fill;
});
});
describe('_resolveAnimations', function() {
function animationsExpectations(anims, props) {
for (const [prop, opts] of Object.entries(props)) {
const anim = anims._properties.get(prop);
expect(anim).withContext(prop).toBeInstanceOf(Object);
if (anim) {
for (const [name, value] of Object.entries(opts)) {
expect(anim[name]).withContext('"' + name + '" of ' + JSON.stringify(anim)).toEqual(value);
}
}
}
}
it('should resolve to empty Animations when globally disabled', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [1],
animation: {
test: {duration: 10}
}
}]
},
options: {
animation: false
}
});
const controller = chart.getDatasetMeta(0).controller;
expect(controller._resolveAnimations(0)._properties.size).toEqual(0);
});
it('should resolve to empty Animations when disabled at dataset level', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [1],
animation: false
}]
}
});
const controller = chart.getDatasetMeta(0).controller;
expect(controller._resolveAnimations(0)._properties.size).toEqual(0);
});
it('should fallback properly', function() {
const chart = acquireChart({
type: 'line',
data: {
datasets: [{
data: [1],
animation: {
duration: 200
}
}, {
type: 'bar',
data: [2]
}]
},
options: {
animation: {
delay: 100
},
animations: {
x: {
delay: 200
}
},
transitions: {
show: {
x: {
delay: 300
}
}
},
datasets: {
bar: {
animation: {
duration: 500
}
}
}
}
});
const controller = chart.getDatasetMeta(0).controller;
expect(Chart.defaults.animation.duration).toEqual(1000);
const def0 = controller._resolveAnimations(0, 'default', false);
animationsExpectations(def0, {
x: {
delay: 200,
duration: 200
},
y: {
delay: 100,
duration: 200
}
});
const controller2 = chart.getDatasetMeta(1).controller;
const def1 = controller2._resolveAnimations(0, 'default', false);
animationsExpectations(def1, {
x: {
delay: 200,
duration: 500
}
});
});
});
describe('getContext', function() {
it('should reflect updated data', function() {
var chart = acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{x: 1, y: 0}, {x: 2, y: '1'}]
}]
},
});
let meta = chart.getDatasetMeta(0);
expect(meta.controller.getContext(undefined, true, 'test')).toEqual(jasmine.objectContaining({
active: true,
datasetIndex: 0,
dataset: chart.data.datasets[0],
index: 0,
mode: 'test'
}));
expect(meta.controller.getContext(1, false, 'datatest')).toEqual(jasmine.objectContaining({
active: false,
datasetIndex: 0,
dataset: chart.data.datasets[0],
dataIndex: 1,
element: meta.data[1],
index: 1,
parsed: {x: 2, y: 1},
raw: {x: 2, y: '1'},
mode: 'datatest'
}));
chart.data.datasets[0].data[1].y = 5;
chart.update();
expect(meta.controller.getContext(1, false, 'datatest')).toEqual(jasmine.objectContaining({
active: false,
datasetIndex: 0,
dataset: chart.data.datasets[0],
dataIndex: 1,
element: meta.data[1],
index: 1,
parsed: {x: 2, y: 5},
raw: {x: 2, y: 5},
mode: 'datatest'
}));
chart.data.datasets = [{
data: [{x: 0, y: 0}, {x: 1, y: 1}]
}];
chart.update();
// meta is re-created when dataset is replaced
meta = chart.getDatasetMeta(0);
expect(meta.controller.getContext(undefined, false, 'test2')).toEqual(jasmine.objectContaining({
active: false,
datasetIndex: 0,
dataset: chart.data.datasets[0],
index: 0,
mode: 'test2'
}));
expect(meta.controller.getContext(1, true, 'datatest2')).toEqual(jasmine.objectContaining({
active: true,
datasetIndex: 0,
dataset: chart.data.datasets[0],
dataIndex: 1,
element: meta.data[1],
index: 1,
parsed: {x: 1, y: 1},
raw: {x: 1, y: 1},
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | true |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.interpolation.tests.js | test/specs/helpers.interpolation.tests.js | const {_pointInLine, _steppedInterpolation, _bezierInterpolation} = Chart.helpers;
describe('helpers.interpolation', function() {
it('Should interpolate a point in line', function() {
expect(_pointInLine({x: 10, y: 10}, {x: 20, y: 20}, 0)).toEqual({x: 10, y: 10});
expect(_pointInLine({x: 10, y: 10}, {x: 20, y: 20}, 0.5)).toEqual({x: 15, y: 15});
expect(_pointInLine({x: 10, y: 10}, {x: 20, y: 20}, 1)).toEqual({x: 20, y: 20});
});
it('Should interpolate a point in stepped line', function() {
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0, 'before')).toEqual({x: 10, y: 10});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0.4, 'before')).toEqual({x: 14, y: 20});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0.5, 'before')).toEqual({x: 15, y: 20});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 1, 'before')).toEqual({x: 20, y: 20});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0, 'middle')).toEqual({x: 10, y: 10});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0.4, 'middle')).toEqual({x: 14, y: 10});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0.5, 'middle')).toEqual({x: 15, y: 20});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 1, 'middle')).toEqual({x: 20, y: 20});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0, 'after')).toEqual({x: 10, y: 10});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0.4, 'after')).toEqual({x: 14, y: 10});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 0.5, 'after')).toEqual({x: 15, y: 10});
expect(_steppedInterpolation({x: 10, y: 10}, {x: 20, y: 20}, 1, 'after')).toEqual({x: 20, y: 20});
});
it('Should interpolate a point in curve', function() {
const pt1 = {x: 10, y: 10, cp2x: 12, cp2y: 12};
const pt2 = {x: 20, y: 30, cp1x: 18, cp1y: 28};
expect(_bezierInterpolation(pt1, pt2, 0)).toEqual({x: 10, y: 10});
expect(_bezierInterpolation(pt1, pt2, 0.2)).toBeCloseToPoint({x: 11.616, y: 12.656});
expect(_bezierInterpolation(pt1, pt2, 1)).toEqual({x: 20, y: 30});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/controller.bar.tests.js | test/specs/controller.bar.tests.js | describe('Chart.controllers.bar', function() {
describe('auto', jasmine.fixture.specs('controller.bar'));
it('should be registered as dataset controller', function() {
expect(typeof Chart.controllers.bar).toBe('function');
});
it('should be constructed', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.type).toEqual('bar');
expect(meta.data).toEqual([]);
expect(meta.hidden).toBe(null);
expect(meta.controller).not.toBe(undefined);
expect(meta.controller.index).toBe(1);
expect(meta.xAxisID).not.toBe(null);
expect(meta.yAxisID).not.toBe(null);
meta.controller.updateIndex(0);
expect(meta.controller.index).toBe(0);
});
it('should set null bars to the reset state', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [10, null, 0, -4],
label: 'dataset1',
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
var bar = meta.data[1];
var {x, y, base} = bar.getProps(['x', 'y', 'base'], true);
expect(isNaN(x)).toBe(false);
expect(isNaN(y)).toBe(false);
expect(isNaN(base)).toBe(false);
});
it('should use the first scale IDs if the dataset does not specify them', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []}
],
labels: []
},
});
var meta = chart.getDatasetMeta(1);
expect(meta.xAxisID).toBe('x');
expect(meta.yAxisID).toBe('y');
});
it('should correctly count the number of stacks ignoring datasets of other types and hidden datasets', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], type: 'line'},
{data: [], hidden: true},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackCount()).toBe(2);
});
it('should correctly count the number of stacks when a group is not specified', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackCount()).toBe(4);
});
it('should correctly count the number of stacks when a group is not specified and the scale is stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackCount()).toBe(1);
});
it('should correctly count the number of stacks when a group is not specified and the scale is not stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
x: {
stacked: false
},
y: {
stacked: false
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackCount()).toBe(4);
});
it('should correctly count the number of stacks when a group is specified for some', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller._getStackCount()).toBe(3);
});
it('should correctly count the number of stacks when a group is specified for some and the scale is stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
}
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller._getStackCount()).toBe(2);
});
it('should correctly count the number of stacks when a group is specified for some and the scale is not stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
x: {
stacked: false
},
y: {
stacked: false
}
}
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller._getStackCount()).toBe(4);
});
it('should correctly count the number of stacks when a group is specified for all', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller._getStackCount()).toBe(2);
});
it('should correctly count the number of stacks when a group is specified for all and the scale is stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
},
options: {
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
}
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller._getStackCount()).toBe(2);
});
it('should correctly count the number of stacks when a group is specified for all and the scale is not stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
},
options: {
scales: {
x: {
stacked: false
},
y: {
stacked: false
}
}
}
});
var meta = chart.getDatasetMeta(3);
expect(meta.controller._getStackCount()).toBe(4);
});
it('should correctly get the stack index accounting for datasets of other types and hidden datasets', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: [], hidden: true},
{data: [], type: 'line'},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(3)).toBe(1);
});
it('should correctly get the stack index when a group is not specified', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(1);
expect(meta.controller._getStackIndex(2)).toBe(2);
expect(meta.controller._getStackIndex(3)).toBe(3);
});
it('should correctly get the stack index when a group is not specified and the scale is stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(0);
expect(meta.controller._getStackIndex(2)).toBe(0);
expect(meta.controller._getStackIndex(3)).toBe(0);
});
it('should correctly get the stack index when a group is not specified and the scale is not stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: []},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
x: {
stacked: false
},
y: {
stacked: false
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(1);
expect(meta.controller._getStackIndex(2)).toBe(2);
expect(meta.controller._getStackIndex(3)).toBe(3);
});
it('should correctly get the stack index when a group is specified for some', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(0);
expect(meta.controller._getStackIndex(2)).toBe(1);
expect(meta.controller._getStackIndex(3)).toBe(2);
});
it('should correctly get the stack index when a group is specified for some and the scale is stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(0);
expect(meta.controller._getStackIndex(2)).toBe(1);
expect(meta.controller._getStackIndex(3)).toBe(1);
});
it('should correctly get the stack index when a group is specified for some and the scale is not stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: []},
{data: []}
],
labels: []
},
options: {
scales: {
x: {
stacked: false
},
y: {
stacked: false
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(1);
expect(meta.controller._getStackIndex(2)).toBe(2);
expect(meta.controller._getStackIndex(3)).toBe(3);
});
it('should correctly get the stack index when a group is specified for all', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(0);
expect(meta.controller._getStackIndex(2)).toBe(1);
expect(meta.controller._getStackIndex(3)).toBe(1);
});
it('should correctly get the stack index when a group is specified for all and the scale is stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
},
options: {
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(0);
expect(meta.controller._getStackIndex(2)).toBe(1);
expect(meta.controller._getStackIndex(3)).toBe(1);
});
it('should correctly get the stack index when a group is specified for all and the scale is not stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [], stack: 'stack1'},
{data: [], stack: 'stack1'},
{data: [], stack: 'stack2'},
{data: [], stack: 'stack2'}
],
labels: []
},
options: {
scales: {
x: {
stacked: false
},
y: {
stacked: false
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.controller._getStackIndex(0)).toBe(0);
expect(meta.controller._getStackIndex(1)).toBe(1);
expect(meta.controller._getStackIndex(2)).toBe(2);
expect(meta.controller._getStackIndex(3)).toBe(3);
});
it('should create bar elements for each data item during initialization', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: []},
{data: [10, 15, 0, -4]}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.data.length).toBe(4); // 4 bars created
expect(meta.data[0] instanceof Chart.elements.BarElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.BarElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.BarElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.BarElement).toBe(true);
});
it('should update elements when modifying data', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
label: 'dataset1'
}, {
data: [10, 15, 0, -4],
label: 'dataset2',
borderColor: 'blue'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
elements: {
bar: {
backgroundColor: 'red',
borderSkipped: 'top',
borderColor: 'green',
borderWidth: 2,
}
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false,
beginAtZero: false
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.data.length).toBe(4);
chart.data.datasets[1].data = [1, 2]; // remove 2 items
chart.data.datasets[1].borderWidth = 1;
chart.update();
expect(meta.data.length).toBe(2);
expect(meta._parsed.length).toBe(2);
[
{x: 89, y: 512},
{x: 217, y: 0}
].forEach(function(expected, i) {
expect(meta.data[i].x).toBeCloseToPixel(expected.x);
expect(meta.data[i].y).toBeCloseToPixel(expected.y);
expect(meta.data[i].base).toBeCloseToPixel(1024);
expect(meta.data[i].width).toBeCloseToPixel(46);
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
backgroundColor: 'red',
borderSkipped: 'top',
borderColor: 'blue',
borderWidth: 1
}));
});
chart.data.datasets[1].data = [1, 2, 3]; // add 1 items
chart.update();
expect(meta.data.length).toBe(3); // should add a new meta data item
});
it('should get the correct bar points when datasets of different types exist', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
label: 'dataset1'
}, {
type: 'line',
data: [4, 6],
label: 'dataset2'
}, {
data: [8, 10],
label: 'dataset3'
}],
labels: ['label1', 'label2']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false,
beginAtZero: false
}
}
}
});
var meta = chart.getDatasetMeta(2);
expect(meta.data.length).toBe(2);
var bar1 = meta.data[0];
var bar2 = meta.data[1];
expect(bar1.x).toBeCloseToPixel(179);
expect(bar1.y).toBeCloseToPixel(117);
expect(bar2.x).toBeCloseToPixel(431);
expect(bar2.y).toBeCloseToPixel(4);
});
it('should get the bar points for hidden dataset', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
label: 'dataset1',
hidden: true
}],
labels: ['label1', 'label2']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
min: 0,
max: 2,
display: false
}
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(2);
var bar1 = meta.data[0];
var bar2 = meta.data[1];
expect(bar1.x).toBeCloseToPixel(128);
expect(bar1.y).toBeCloseToPixel(256);
expect(bar2.x).toBeCloseToPixel(384);
expect(bar2.y).toBeCloseToPixel(0);
});
it('should update elements when the scales are stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [10, -10, 10, -10],
label: 'dataset1'
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false,
stacked: true
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 293, w: 92 / 2, x: 38, y: 146},
{b: 293, w: 92 / 2, x: 166, y: 439},
{b: 293, w: 92 / 2, x: 295, y: 146},
{b: 293, w: 92 / 2, x: 422, y: 439}
].forEach(function(values, i) {
expect(meta0.data[i].base).toBeCloseToPixel(values.b);
expect(meta0.data[i].width).toBeCloseToPixel(values.w);
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 146, w: 92 / 2, x: 89, y: 0},
{b: 293, w: 92 / 2, x: 217, y: 73},
{b: 146, w: 92 / 2, x: 345, y: 146},
{b: 439, w: 92 / 2, x: 473, y: 497}
].forEach(function(values, i) {
expect(meta1.data[i].base).toBeCloseToPixel(values.b);
expect(meta1.data[i].width).toBeCloseToPixel(values.w);
expect(meta1.data[i].x).toBeCloseToPixel(values.x);
expect(meta1.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should update elements when the scales are stacked and the y axis has a user defined minimum', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [50, 20, 10, 100],
label: 'dataset1'
}, {
data: [50, 80, 90, 0],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false,
stacked: true,
min: 50,
max: 100
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 1024, w: 92 / 2, x: 38, y: 512},
{b: 1024, w: 92 / 2, x: 166, y: 819},
{b: 1024, w: 92 / 2, x: 294, y: 922},
{b: 1024, w: 92 / 2, x: 422.5, y: 0}
].forEach(function(values, i) {
expect(meta0.data[i].base).toBeCloseToPixel(values.b);
expect(meta0.data[i].width).toBeCloseToPixel(values.w);
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 512, w: 92 / 2, x: 89, y: 0},
{b: 819.2, w: 92 / 2, x: 217, y: 0},
{b: 921.6, w: 92 / 2, x: 345, y: 0},
{b: 0, w: 92 / 2, x: 473.5, y: 0}
].forEach(function(values, i) {
expect(meta1.data[i].base).toBeCloseToPixel(values.b);
expect(meta1.data[i].width).toBeCloseToPixel(values.w);
expect(meta1.data[i].x).toBeCloseToPixel(values.x);
expect(meta1.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should update elements when only the category scale is stacked', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [20, -10, 10, -10],
label: 'dataset1'
}, {
data: [10, 15, 0, -14],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false,
stacked: true
},
y: {
type: 'linear',
display: false
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 293, w: 92, x: 64, y: 0},
{b: 293, w: 92, x: 192, y: 439},
{b: 293, w: 92, x: 320, y: 146},
{b: 293, w: 92, x: 448, y: 439}
].forEach(function(values, i) {
expect(meta0.data[i].base).toBeCloseToPixel(values.b);
expect(meta0.data[i].width).toBeCloseToPixel(values.w);
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 293, w: 92, x: 64, y: 146},
{b: 293, w: 92, x: 192, y: 73},
{b: 293, w: 92, x: 320, y: 293},
{b: 293, w: 92, x: 448, y: 497}
].forEach(function(values, i) {
expect(meta1.data[i].base).toBeCloseToPixel(values.b);
expect(meta1.data[i].width).toBeCloseToPixel(values.w);
expect(meta1.data[i].x).toBeCloseToPixel(values.x);
expect(meta1.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should update elements when the scales are stacked and data is strings', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: ['10', '-10', '10', '-10'],
label: 'dataset1'
}, {
data: ['10', '15', '0', '-4'],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false,
stacked: true
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 293, w: 92 / 2, x: 38, y: 146},
{b: 293, w: 92 / 2, x: 166, y: 439},
{b: 293, w: 92 / 2, x: 295, y: 146},
{b: 293, w: 92 / 2, x: 422, y: 439}
].forEach(function(values, i) {
expect(meta0.data[i].base).toBeCloseToPixel(values.b);
expect(meta0.data[i].width).toBeCloseToPixel(values.w);
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{b: 146, w: 92 / 2, x: 89, y: 0},
{b: 293, w: 92 / 2, x: 217, y: 73},
{b: 146, w: 92 / 2, x: 345, y: 146},
{b: 439, w: 92 / 2, x: 473, y: 497}
].forEach(function(values, i) {
expect(meta1.data[i].base).toBeCloseToPixel(values.b);
expect(meta1.data[i].width).toBeCloseToPixel(values.w);
expect(meta1.data[i].x).toBeCloseToPixel(values.x);
expect(meta1.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should get the correct bar points for grouped stacked chart if the group name is same', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [10, -10, 10, -10],
label: 'dataset1',
stack: 'stack1'
}, {
data: [10, 15, 0, -4],
label: 'dataset2',
stack: 'stack1'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false,
stacked: true
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{b: 293, w: 92, x: 64, y: 146},
{b: 293, w: 92, x: 192, y: 439},
{b: 293, w: 92, x: 320, y: 146},
{b: 293, w: 92, x: 448, y: 439}
].forEach(function(values, i) {
expect(meta0.data[i].base).toBeCloseToPixel(values.b);
expect(meta0.data[i].width).toBeCloseToPixel(values.w);
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta = chart.getDatasetMeta(1);
[
{b: 146, w: 92, x: 64, y: 0},
{b: 293, w: 92, x: 192, y: 73},
{b: 146, w: 92, x: 320, y: 146},
{b: 439, w: 92, x: 448, y: 497}
].forEach(function(values, i) {
expect(meta.data[i].base).toBeCloseToPixel(values.b);
expect(meta.data[i].width).toBeCloseToPixel(values.w);
expect(meta.data[i].x).toBeCloseToPixel(values.x);
expect(meta.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should get the correct bar points for grouped stacked chart if the group name is different', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
stack: 'stack1'
}, {
data: [1, 2],
stack: 'stack2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false,
stacked: true,
}
}
}
});
var meta = chart.getDatasetMeta(1);
[
{x: 89, y: 256},
{x: 217, y: 0}
].forEach(function(values, i) {
expect(meta.data[i].base).toBeCloseToPixel(512);
expect(meta.data[i].width).toBeCloseToPixel(46);
expect(meta.data[i].x).toBeCloseToPixel(values.x);
expect(meta.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should get the correct bar points for grouped stacked chart', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 2],
stack: 'stack1'
}, {
data: [0.5, 1],
stack: 'stack2'
}, {
data: [0.5, 1],
stack: 'stack2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false,
stacked: true
}
}
}
});
var meta = chart.getDatasetMeta(2);
[
{b: 384, x: 89, y: 256},
{b: 256, x: 217, y: 0}
].forEach(function(values, i) {
expect(meta.data[i].base).toBeCloseToPixel(values.b);
expect(meta.data[i].width).toBeCloseToPixel(46);
expect(meta.data[i].x).toBeCloseToPixel(values.x);
expect(meta.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should draw all bars', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [],
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(1);
spyOn(meta.data[0], 'draw');
spyOn(meta.data[1], 'draw');
spyOn(meta.data[2], 'draw');
spyOn(meta.data[3], 'draw');
chart.update();
expect(meta.data[0].draw.calls.count()).toBe(1);
expect(meta.data[1].draw.calls.count()).toBe(1);
expect(meta.data[2].draw.calls.count()).toBe(1);
expect(meta.data[3].draw.calls.count()).toBe(1);
});
it('should set hover styles on bars', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [],
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
elements: {
bar: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2,
}
}
}
});
var meta = chart.getDatasetMeta(1);
var bar = meta.data[0];
meta.controller.setHoverStyle(bar, 1, 0);
expect(bar.options.backgroundColor).toBe('#E60000');
expect(bar.options.borderColor).toBe('#0000E6');
expect(bar.options.borderWidth).toBe(2);
// Set a dataset style
chart.data.datasets[1].hoverBackgroundColor = 'rgb(128, 128, 128)';
chart.data.datasets[1].hoverBorderColor = 'rgb(0, 0, 0)';
chart.data.datasets[1].hoverBorderWidth = 5;
chart.update();
meta.controller.setHoverStyle(bar, 1, 0);
expect(bar.options.backgroundColor).toBe('rgb(128, 128, 128)');
expect(bar.options.borderColor).toBe('rgb(0, 0, 0)');
expect(bar.options.borderWidth).toBe(5);
// Should work with array styles so that we can set per bar
chart.data.datasets[1].hoverBackgroundColor = ['rgb(255, 255, 255)', 'rgb(128, 128, 128)'];
chart.data.datasets[1].hoverBorderColor = ['rgb(9, 9, 9)', 'rgb(0, 0, 0)'];
chart.data.datasets[1].hoverBorderWidth = [2.5, 5];
chart.update();
meta.controller.setHoverStyle(bar, 1, 0);
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | true |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/controller.doughnut.tests.js | test/specs/controller.doughnut.tests.js | describe('Chart.controllers.doughnut', function() {
describe('auto', jasmine.fixture.specs('controller.doughnut'));
it('should be registered as dataset controller', function() {
expect(typeof Chart.controllers.doughnut).toBe('function');
expect(typeof Chart.controllers.pie).toBe('function');
});
it('should be constructed', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
datasets: [{
data: []
}],
labels: []
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.type).toBe('doughnut');
expect(meta.controller).not.toBe(undefined);
expect(meta.controller.index).toBe(0);
expect(meta.data).toEqual([]);
meta.controller.updateIndex(1);
expect(meta.controller.index).toBe(1);
});
it('should create arc elements for each data item during initialization', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
datasets: [{
data: [10, 15, 0, 4]
}],
labels: []
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4); // 4 arcs created
expect(meta.data[0] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.ArcElement).toBe(true);
});
it ('should reset and update elements', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
datasets: [{
data: [1, 2, 3, 4],
hidden: true
}, {
data: [5, 6, 0, 7]
}, {
data: [8, 9, 10, 11]
}],
labels: ['label0', 'label1', 'label2', 'label3']
},
options: {
plugins: {
legend: false,
title: false,
},
animation: {
duration: 0,
animateRotate: true,
animateScale: false
},
cutout: '50%',
rotation: 0,
circumference: 360,
elements: {
arc: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2
}
}
}
});
var meta = chart.getDatasetMeta(1);
meta.controller.reset(); // reset first
expect(meta.data.length).toBe(4);
[
{c: 0},
{c: 0},
{c: 0},
{c: 0}
].forEach(function(expected, i) {
expect(meta.data[i].x).toBeCloseToPixel(256);
expect(meta.data[i].y).toBeCloseToPixel(256);
expect(meta.data[i].outerRadius).toBeCloseToPixel(256);
expect(meta.data[i].innerRadius).toBeCloseToPixel(192);
expect(meta.data[i].circumference).toBeCloseTo(expected.c, 8);
expect(meta.data[i].startAngle).toBeCloseToPixel(Math.PI * -0.5);
expect(meta.data[i].endAngle).toBeCloseToPixel(Math.PI * -0.5);
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2
}));
});
chart.update();
[
{c: 1.7453292519, s: -1.5707963267, e: 0.1745329251},
{c: 2.0943951023, s: 0.1745329251, e: 2.2689280275},
{c: 0, s: 2.2689280275, e: 2.2689280275},
{c: 2.4434609527, s: 2.2689280275, e: 4.7123889803}
].forEach(function(expected, i) {
expect(meta.data[i].x).toBeCloseToPixel(256);
expect(meta.data[i].y).toBeCloseToPixel(256);
expect(meta.data[i].outerRadius).toBeCloseToPixel(256);
expect(meta.data[i].innerRadius).toBeCloseToPixel(192);
expect(meta.data[i].circumference).toBeCloseTo(expected.c, 8);
expect(meta.data[i].startAngle).toBeCloseTo(expected.s, 8);
expect(meta.data[i].endAngle).toBeCloseTo(expected.e, 8);
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2
}));
});
// Change the amount of data and ensure that arcs are updated accordingly
chart.data.datasets[1].data = [1, 2]; // remove 2 elements from dataset 0
chart.update();
expect(meta.data.length).toBe(2);
expect(meta.data[0] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.ArcElement).toBe(true);
// Add data
chart.data.datasets[1].data = [1, 2, 3, 4];
chart.update();
expect(meta.data.length).toBe(4);
expect(meta.data[0] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.ArcElement).toBe(true);
});
it ('should rotate and limit circumference', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
datasets: [{
data: [2, 4],
hidden: true
}, {
data: [1, 3]
}, {
data: [1, 0]
}],
labels: ['label0', 'label1', 'label2']
},
options: {
plugins: {
legend: false,
title: false,
},
cutout: '50%',
rotation: 270,
circumference: 90,
elements: {
arc: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2
}
}
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.data.length).toBe(2);
// Only startAngle, endAngle and circumference should be different.
[
{c: Math.PI / 8, s: Math.PI, e: Math.PI + Math.PI / 8},
{c: 3 * Math.PI / 8, s: Math.PI + Math.PI / 8, e: Math.PI + Math.PI / 2}
].forEach(function(expected, i) {
expect(meta.data[i].x).toBeCloseToPixel(512);
expect(meta.data[i].y).toBeCloseToPixel(512);
expect(meta.data[i].outerRadius).toBeCloseToPixel(512);
expect(meta.data[i].innerRadius).toBeCloseToPixel(384);
expect(meta.data[i].circumference).toBeCloseTo(expected.c, 8);
expect(meta.data[i].startAngle).toBeCloseTo(expected.s, 8);
expect(meta.data[i].endAngle).toBeCloseTo(expected.e, 8);
});
});
it('should treat negative values as positive', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
datasets: [{
data: [-1, -3]
}],
labels: ['label0', 'label1']
},
options: {
plugins: {
legend: false,
title: false
},
cutout: '50%',
rotation: 270,
circumference: 90,
elements: {
arc: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 0, 255)',
borderWidth: 2
}
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(2);
// Only startAngle, endAngle and circumference should be different.
[
{c: Math.PI / 8, s: Math.PI, e: Math.PI + Math.PI / 8},
{c: 3 * Math.PI / 8, s: Math.PI + Math.PI / 8, e: Math.PI + Math.PI / 2}
].forEach(function(expected, i) {
expect(meta.data[i].circumference).toBeCloseTo(expected.c, 8);
expect(meta.data[i].startAngle).toBeCloseTo(expected.s, 8);
expect(meta.data[i].endAngle).toBeCloseTo(expected.e, 8);
});
});
it ('should draw all arcs', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
datasets: [{
data: [10, 15, 0, 4]
}],
labels: ['label0', 'label1', 'label2', 'label3']
}
});
var meta = chart.getDatasetMeta(0);
spyOn(meta.data[0], 'draw');
spyOn(meta.data[1], 'draw');
spyOn(meta.data[2], 'draw');
spyOn(meta.data[3], 'draw');
chart.update();
expect(meta.data[0].draw.calls.count()).toBe(1);
expect(meta.data[1].draw.calls.count()).toBe(1);
expect(meta.data[2].draw.calls.count()).toBe(1);
expect(meta.data[3].draw.calls.count()).toBe(1);
});
it ('should calculate radiuses based on the border widths of the visible outermost dataset', function() {
var chart = window.acquireChart({
type: 'doughnut',
data: {
datasets: [{
data: [2, 4],
borderWidth: 4,
hidden: true
}, {
data: [1, 3],
borderWidth: 8
}, {
data: [1, 0],
borderWidth: 12
}],
labels: ['label0', 'label1']
},
options: {
plugins: {
legend: false,
title: false
}
}
});
chart.update();
var controller = chart.getDatasetMeta(0).controller;
expect(chart.chartArea.bottom - chart.chartArea.top).toBe(512);
expect(controller.getMaxBorderWidth()).toBe(8);
expect(controller.outerRadius).toBe(252);
expect(controller.innerRadius).toBe(189);
controller = chart.getDatasetMeta(1).controller;
expect(controller.getMaxBorderWidth()).toBe(8);
expect(controller.outerRadius).toBe(252);
expect(controller.innerRadius).toBe(189);
controller = chart.getDatasetMeta(2).controller;
expect(controller.getMaxBorderWidth()).toBe(8);
expect(controller.outerRadius).toBe(189);
expect(controller.innerRadius).toBe(126);
});
describe('Interactions', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'doughnut',
data: {
labels: ['label1', 'label2', 'label3', 'label4'],
datasets: [{
data: [10, 15, 0, 4]
}]
},
options: {
cutout: '50%',
elements: {
arc: {
backgroundColor: 'rgb(100, 150, 200)',
borderColor: 'rgb(50, 100, 150)',
borderWidth: 2,
}
}
}
});
});
it ('should handle default hover styles', async function() {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', arc);
expect(arc.options.backgroundColor).toBe('#3187DD');
expect(arc.options.borderColor).toBe('#175A9D');
expect(arc.options.borderWidth).toBe(2);
await jasmine.triggerMouseEvent(chart, 'mouseout', arc);
expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
expect(arc.options.borderWidth).toBe(2);
});
it ('should handle hover styles defined via dataset properties', async function() {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.data.datasets[0], {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', arc);
expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
expect(arc.options.borderWidth).toBe(8.4);
await jasmine.triggerMouseEvent(chart, 'mouseout', arc);
expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
expect(arc.options.borderWidth).toBe(2);
});
it ('should handle hover styles defined via element options', async function() {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.options.elements.arc, {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', arc);
expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
expect(arc.options.borderWidth).toBe(8.4);
await jasmine.triggerMouseEvent(chart, 'mouseout', arc);
expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
expect(arc.options.borderWidth).toBe(2);
});
});
it('should not override tooltip title and label callbacks', async() => {
const chart = window.acquireChart({
type: 'doughnut',
data: {
labels: ['Label 1', 'Label 2'],
datasets: [{
data: [21, 79],
label: 'Dataset 1'
}, {
data: [33, 67],
label: 'Dataset 2'
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
}
});
const {tooltip} = chart;
const point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Label 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Dataset 1: 21'],
after: []
}]);
chart.options.plugins.tooltip = {mode: 'dataset'};
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Dataset 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Label 1: 21'],
after: []
}, {
before: [],
lines: ['Label 2: 79'],
after: []
}]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.registry.tests.js | test/specs/core.registry.tests.js | describe('Chart.registry', function() {
it('should handle an ES6 controller extension', function() {
class CustomController extends Chart.DatasetController {}
CustomController.id = 'custom';
CustomController.defaults = {
foo: 'bar'
};
CustomController.overrides = {
bar: 'foo'
};
Chart.register(CustomController);
expect(Chart.registry.getController('custom')).toEqual(CustomController);
expect(Chart.defaults.datasets.custom).toEqual(CustomController.defaults);
expect(Chart.overrides.custom).toEqual(CustomController.overrides);
Chart.unregister(CustomController);
expect(function() {
Chart.registry.getController('custom');
}).toThrow(new Error('"custom" is not a registered controller.'));
expect(Chart.overrides.custom).not.toBeDefined();
expect(Chart.defaults.datasets.custom).not.toBeDefined();
});
it('should handle an ES6 scale extension', function() {
class CustomScale extends Chart.Scale {}
CustomScale.id = 'es6Scale';
CustomScale.defaults = {
foo: 'bar'
};
Chart.register(CustomScale);
expect(Chart.registry.getScale('es6Scale')).toEqual(CustomScale);
expect(Chart.defaults.scales.es6Scale).toEqual(CustomScale.defaults);
Chart.unregister(CustomScale);
expect(function() {
Chart.registry.getScale('es6Scale');
}).toThrow(new Error('"es6Scale" is not a registered scale.'));
expect(Chart.defaults.scales.es6Scale).not.toBeDefined();
});
it('should handle an ES6 element extension', function() {
class CustomElement extends Chart.Element {}
CustomElement.id = 'es6element';
CustomElement.defaults = {
foo: 'bar'
};
Chart.register(CustomElement);
expect(Chart.registry.getElement('es6element')).toEqual(CustomElement);
expect(Chart.defaults.elements.es6element).toEqual(CustomElement.defaults);
Chart.unregister(CustomElement);
expect(function() {
Chart.registry.getElement('es6element');
}).toThrow(new Error('"es6element" is not a registered element.'));
expect(Chart.defaults.elements.es6element).not.toBeDefined();
});
it('should handle an ES6 plugin', function() {
class CustomPlugin {}
CustomPlugin.id = 'es6plugin';
CustomPlugin.defaults = {
foo: 'bar'
};
Chart.register(CustomPlugin);
expect(Chart.registry.getPlugin('es6plugin')).toEqual(CustomPlugin);
expect(Chart.defaults.plugins.es6plugin).toEqual(CustomPlugin.defaults);
Chart.unregister(CustomPlugin);
expect(function() {
Chart.registry.getPlugin('es6plugin');
}).toThrow(new Error('"es6plugin" is not a registered plugin.'));
expect(Chart.defaults.plugins.es6plugin).not.toBeDefined();
});
it('should not accept an object without id', function() {
expect(function() {
Chart.register({foo: 'bar'});
}).toThrow(new Error('class does not have id: bar'));
class FaultyPlugin {}
expect(function() {
Chart.register(FaultyPlugin);
}).toThrow(new Error('class does not have id: class FaultyPlugin {}'));
});
it('should not fail when unregistering an object that is not registered', function() {
expect(function() {
Chart.unregister({id: 'foo'});
}).not.toThrow();
});
describe('Should allow registering explicitly', function() {
class customExtension {}
customExtension.id = 'custom';
customExtension.defaults = {
prop: true
};
it('as controller', function() {
Chart.registry.addControllers(customExtension);
expect(Chart.registry.getController('custom')).toEqual(customExtension);
expect(Chart.defaults.datasets.custom).toEqual(customExtension.defaults);
Chart.registry.removeControllers(customExtension);
expect(function() {
Chart.registry.getController('custom');
}).toThrow(new Error('"custom" is not a registered controller.'));
expect(Chart.defaults.datasets.custom).not.toBeDefined();
});
it('as scale', function() {
Chart.registry.addScales(customExtension);
expect(Chart.registry.getScale('custom')).toEqual(customExtension);
expect(Chart.defaults.scales.custom).toEqual(customExtension.defaults);
Chart.registry.removeScales(customExtension);
expect(function() {
Chart.registry.getScale('custom');
}).toThrow(new Error('"custom" is not a registered scale.'));
expect(Chart.defaults.scales.custom).not.toBeDefined();
});
it('as element', function() {
Chart.registry.addElements(customExtension);
expect(Chart.registry.getElement('custom')).toEqual(customExtension);
expect(Chart.defaults.elements.custom).toEqual(customExtension.defaults);
Chart.registry.removeElements(customExtension);
expect(function() {
Chart.registry.getElement('custom');
}).toThrow(new Error('"custom" is not a registered element.'));
expect(Chart.defaults.elements.custom).not.toBeDefined();
});
it('as plugin', function() {
Chart.registry.addPlugins(customExtension);
expect(Chart.registry.getPlugin('custom')).toEqual(customExtension);
expect(Chart.defaults.plugins.custom).toEqual(customExtension.defaults);
Chart.registry.removePlugins(customExtension);
expect(function() {
Chart.registry.getPlugin('custom');
}).toThrow(new Error('"custom" is not a registered plugin.'));
expect(Chart.defaults.plugins.custom).not.toBeDefined();
});
});
it('should fire before/after callbacks', function() {
let beforeRegisterCount = 0;
let afterRegisterCount = 0;
let beforeUnregisterCount = 0;
let afterUnregisterCount = 0;
class custom {}
custom.id = 'custom';
custom.beforeRegister = () => beforeRegisterCount++;
custom.afterRegister = () => afterRegisterCount++;
custom.beforeUnregister = () => beforeUnregisterCount++;
custom.afterUnregister = () => afterUnregisterCount++;
Chart.registry.addControllers(custom);
expect(beforeRegisterCount).withContext('beforeRegister').toBe(1);
expect(afterRegisterCount).withContext('afterRegister').toBe(1);
Chart.registry.removeControllers(custom);
expect(beforeUnregisterCount).withContext('beforeUnregister').toBe(1);
expect(afterUnregisterCount).withContext('afterUnregister').toBe(1);
Chart.registry.addScales(custom);
expect(beforeRegisterCount).withContext('beforeRegister').toBe(2);
expect(afterRegisterCount).withContext('afterRegister').toBe(2);
Chart.registry.removeScales(custom);
expect(beforeUnregisterCount).withContext('beforeUnregister').toBe(2);
expect(afterUnregisterCount).withContext('afterUnregister').toBe(2);
Chart.registry.addElements(custom);
expect(beforeRegisterCount).withContext('beforeRegister').toBe(3);
expect(afterRegisterCount).withContext('afterRegister').toBe(3);
Chart.registry.removeElements(custom);
expect(beforeUnregisterCount).withContext('beforeUnregister').toBe(3);
expect(afterUnregisterCount).withContext('afterUnregister').toBe(3);
Chart.register(custom);
expect(beforeRegisterCount).withContext('beforeRegister').toBe(4);
expect(afterRegisterCount).withContext('afterRegister').toBe(4);
Chart.unregister(custom);
expect(beforeUnregisterCount).withContext('beforeUnregister').toBe(4);
expect(afterUnregisterCount).withContext('afterUnregister').toBe(4);
});
it('should preserve existing defaults', function() {
Chart.defaults.datasets.test = {test1: true, test3: false};
Chart.overrides.test = {testA: true, testC: false};
class testController extends Chart.DatasetController {}
testController.id = 'test';
testController.defaults = {test1: false, test2: true};
testController.overrides = {testA: false, testB: true};
Chart.register(testController);
expect(Chart.defaults.datasets.test).toEqual({test1: false, test2: true, test3: false});
expect(Chart.overrides.test).toEqual({testA: false, testB: true, testC: false});
Chart.unregister(testController);
expect(Chart.defaults.datasets.test).not.toBeDefined();
expect(Chart.overrides.test).not.toBeDefined();
});
describe('should handle multiple items', function() {
class test1 extends Chart.DatasetController {}
test1.id = 'test1';
class test2 extends Chart.Scale {}
test2.id = 'test2';
it('separately', function() {
Chart.register(test1, test2);
expect(Chart.registry.getController('test1')).toEqual(test1);
expect(Chart.registry.getScale('test2')).toEqual(test2);
Chart.unregister(test1, test2);
expect(function() {
Chart.registry.getController('test1');
}).toThrow();
expect(function() {
Chart.registry.getScale('test2');
}).toThrow();
});
it('as array', function() {
Chart.register([test1, test2]);
expect(Chart.registry.getController('test1')).toEqual(test1);
expect(Chart.registry.getScale('test2')).toEqual(test2);
Chart.unregister([test1, test2]);
expect(function() {
Chart.registry.getController('test1');
}).toThrow();
expect(function() {
Chart.registry.getScale('test2');
}).toThrow();
});
it('as object', function() {
Chart.register({test1, test2});
expect(Chart.registry.getController('test1')).toEqual(test1);
expect(Chart.registry.getScale('test2')).toEqual(test2);
Chart.unregister({test1, test2});
expect(function() {
Chart.registry.getController('test1');
}).toThrow();
expect(function() {
Chart.registry.getScale('test2');
}).toThrow();
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/plugin.decimation.tests.js | test/specs/plugin.decimation.tests.js | describe('Plugin.decimation', function() {
describe('auto', jasmine.fixture.specs('plugin.decimation'));
describe('lttb', function() {
const originalData = [
{x: 0, y: 0},
{x: 1, y: 1},
{x: 2, y: 2},
{x: 3, y: 3},
{x: 4, y: 4},
{x: 5, y: 5},
{x: 6, y: 6},
{x: 7, y: 7},
{x: 8, y: 8},
{x: 9, y: 9}];
it('should draw all element if sample is greater than data based on canvas width', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: originalData,
label: 'dataset1'
}]
},
scales: {
x: {
type: 'linear',
min: 0,
max: 9
}
},
options: {
plugins: {
decimation: {
enabled: true,
algorithm: 'lttb',
samples: 100
}
}
}
}, {
canvas: {
height: 1,
width: 1
},
wrapper: {
height: 1,
width: 1
}
});
expect(chart.data.datasets[0].data.length).toBe(10);
});
it('should draw the specified number of elements based on canvas width', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: originalData,
label: 'dataset1'
}]
},
options: {
parsing: false,
scales: {
x: {
type: 'linear',
min: 0,
max: 9
}
},
plugins: {
decimation: {
enabled: true,
algorithm: 'lttb',
samples: 7
}
}
}
}, {
canvas: {
height: 1,
width: 1
},
wrapper: {
height: 1,
width: 1
}
});
expect(chart.data.datasets[0].data.length).toBe(7);
});
it('should draw the specified number of elements based on threshold', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: originalData,
label: 'dataset1'
}]
},
options: {
parsing: false,
scales: {
x: {
type: 'linear'
}
},
plugins: {
decimation: {
enabled: true,
algorithm: 'lttb',
samples: 5,
threshold: 7
}
}
}
}, {
canvas: {
height: 100,
width: 100
},
wrapper: {
height: 100,
width: 100
}
});
expect(chart.data.datasets[0].data.length).toBe(5);
});
it('should draw all element only in range', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: originalData,
label: 'dataset1'
}]
},
options: {
parsing: false,
scales: {
x: {
type: 'linear',
min: 3,
max: 6
}
},
plugins: {
decimation: {
enabled: true,
algorithm: 'lttb',
samples: 7
}
}
}
}, {
canvas: {
height: 1,
width: 1
},
wrapper: {
height: 1,
width: 1
}
});
// Data range is 4 (3->6) and the first point is added
const expectedPoints = 5;
expect(chart.data.datasets[0].data.length).toBe(expectedPoints);
expect(chart.data.datasets[0].data[0].x).toBe(originalData[2].x);
expect(chart.data.datasets[0].data[1].x).toBe(originalData[3].x);
expect(chart.data.datasets[0].data[2].x).toBe(originalData[4].x);
expect(chart.data.datasets[0].data[3].x).toBe(originalData[5].x);
expect(chart.data.datasets[0].data[4].x).toBe(originalData[6].x);
});
it('should not crash with uneven points', function() {
const data = [];
for (let i = 0; i < 15552; i++) {
data.push({x: i, y: i});
}
function createChart() {
return window.acquireChart({
type: 'line',
data: {
datasets: [{
data
}]
},
options: {
devicePixelRatio: 1.25,
parsing: false,
scales: {
x: {
type: 'linear'
}
},
plugins: {
decimation: {
enabled: true,
algorithm: 'lttb'
}
}
}
}, {
canvas: {width: 511, height: 511},
});
}
expect(createChart).not.toThrow();
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.color.tests.js | test/specs/helpers.color.tests.js | const {color, getHoverColor} = Chart.helpers;
describe('Color helper', function() {
function isColorInstance(obj) {
return typeof obj === 'object' && obj.valid;
}
it('should return a color when called with a color', function() {
expect(isColorInstance(color('rgb(1, 2, 3)'))).toBe(true);
});
});
describe('Background hover color helper', function() {
it('should return a modified version of color when called with a color', function() {
var originalColorRGB = 'rgb(70, 191, 189)';
expect(getHoverColor('#46BFBD')).not.toEqual(originalColorRGB);
});
});
describe('color and getHoverColor helpers', function() {
it('should return a CanvasPattern when called with a CanvasPattern', function(done) {
var dots = new Image();
dots.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAMAAAAolt3jAAAAD1BMVEUAAAD///////////////+PQt5oAAAABXRSTlMAHlFhZsfk/BEAAAAqSURBVHgBY2BgZGJmYmSAAUYWEIDzmcBcJhiXGcxlRpPFrhdmMiqgvX0AcGIBEUAo6UAAAAAASUVORK5CYII=';
dots.onload = function() {
var chartContext = document.createElement('canvas').getContext('2d');
var patternCanvas = document.createElement('canvas');
var patternContext = patternCanvas.getContext('2d');
var pattern = patternContext.createPattern(dots, 'repeat');
patternContext.fillStyle = pattern;
var chartPattern = chartContext.createPattern(patternCanvas, 'repeat');
expect(color(chartPattern) instanceof CanvasPattern).toBe(true);
expect(getHoverColor(chartPattern) instanceof CanvasPattern).toBe(true);
done();
};
});
it('should return a CanvasGradient when called with a CanvasGradient', function() {
var context = document.createElement('canvas').getContext('2d');
var gradient = context.createLinearGradient(0, 1, 2, 3);
expect(color(gradient) instanceof CanvasGradient).toBe(true);
expect(getHoverColor(gradient) instanceof CanvasGradient).toBe(true);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.config.tests.js | test/specs/helpers.config.tests.js | describe('Chart.helpers.config', function() {
const {getHoverColor, _createResolver, _attachContext} = Chart.helpers;
describe('_createResolver', function() {
it('should resolve to raw values', function() {
const defaults = {
color: 'red',
backgroundColor: 'green',
hoverColor: (ctx, options) => getHoverColor(options.color)
};
const options = {
color: 'blue'
};
const resolver = _createResolver([options, defaults]);
expect(resolver.color).toEqual('blue');
expect(resolver.backgroundColor).toEqual('green');
expect(resolver.hoverColor).toEqual(defaults.hoverColor);
});
it('should resolve to parent scopes, when _fallback is true', function() {
const descriptors = {
_fallback: true
};
const defaults = {
root: true,
sub: {
child: true
}
};
const options = {
child: 'sub default comes before this',
opt: 'opt'
};
const resolver = _createResolver([options, defaults, descriptors]);
const sub = resolver.sub;
expect(sub.root).toEqual(true);
expect(sub.child).toEqual(true);
expect(sub.opt).toEqual('opt');
});
it('should support overriding options', function() {
const defaults = {
option1: 'defaults1',
option2: 'defaults2',
option3: 'defaults3',
};
const options = {
option1: 'options1',
option2: 'options2'
};
const overrides = {
option1: 'override1'
};
const resolver = _createResolver([options, defaults]);
expect(resolver).toEqualOptions({
option1: 'options1',
option2: 'options2',
option3: 'defaults3'
});
expect(resolver.override(overrides)).toEqualOptions({
option1: 'override1',
option2: 'options2',
option3: 'defaults3'
});
});
it('should support common object methods', function() {
const defaults = {
option1: 'defaults'
};
class Options {
constructor() {
this.option2 = 'options';
}
get getter() {
return 'options getter';
}
}
const options = new Options();
const resolver = _createResolver([options, defaults]);
expect(Object.prototype.hasOwnProperty.call(resolver, 'option2')).toBeTrue();
expect(Object.prototype.hasOwnProperty.call(resolver, 'option1')).toBeFalse();
expect(Object.prototype.hasOwnProperty.call(resolver, 'getter')).toBeFalse();
expect(Object.prototype.hasOwnProperty.call(resolver, 'nonexistent')).toBeFalse();
expect(Object.keys(resolver)).toEqual(['option2']);
expect(Object.getOwnPropertyNames(resolver)).toEqual(['option2', 'option1']);
expect('option2' in resolver).toBeTrue();
expect('option1' in resolver).toBeTrue();
expect('getter' in resolver).toBeFalse();
expect('nonexistent' in resolver).toBeFalse();
expect(resolver instanceof Options).toBeTrue();
expect(resolver.getter).toEqual('options getter');
});
it('should not fail on when options are frozen', function() {
function create() {
const defaults = Object.freeze({default: true});
const options = Object.freeze({value: true});
return _createResolver([options, defaults]);
}
expect(create).not.toThrow();
});
describe('_fallback', function() {
it('should follow simple _fallback', function() {
const defaults = {
interaction: {
mode: 'test',
priority: 'fall'
},
hover: {
_fallback: 'interaction',
priority: 'main'
}
};
const options = {
interaction: {
a: 1
},
hover: {
b: 2
}
};
const resolver = _createResolver([options, defaults]);
expect(resolver.hover).toEqualOptions({
mode: 'test',
priority: 'main',
a: 1,
b: 2
});
});
it('should support _fallback as function', function() {
const descriptors = {
_fallback: (prop, value) => prop === 'hover' && value.shouldFall && 'interaction',
};
const defaults = {
interaction: {
mode: 'test',
priority: 'fall'
},
hover: {
priority: 'main'
}
};
const options = {
interaction: {
a: 1
},
hover: {
shouldFall: true,
b: 2
}
};
const resolver = _createResolver([options, defaults, descriptors]);
expect(resolver.hover).toEqualOptions({
mode: 'test',
priority: 'main',
a: 1,
b: 2
});
});
it('should not fallback by default', function() {
const defaults = {
hover: {
a: 'defaults.hover'
},
controllers: {
y: 'defaults.controllers',
bar: {
z: 'defaults.controllers.bar',
hover: {
b: 'defaults.controllers.bar.hover'
}
}
},
x: 'defaults root'
};
const options = {
x: 'options',
hover: {
c: 'options.hover',
sub: {
f: 'options.hover.sub'
}
},
controllers: {
y: 'options.controllers',
bar: {
z: 'options.controllers.bar',
hover: {
d: 'options.controllers.bar.hover',
sub: {
e: 'options.controllers.bar.hover.sub'
}
}
}
}
};
const resolver = _createResolver([options, options.controllers.bar, options.controllers, defaults.controllers.bar, defaults.controllers, defaults]);
expect(resolver.hover).toEqualOptions({
a: 'defaults.hover',
b: 'defaults.controllers.bar.hover',
c: 'options.hover',
d: 'options.controllers.bar.hover',
e: undefined,
f: undefined,
x: undefined,
y: undefined,
z: undefined
});
expect(resolver.hover.sub).toEqualOptions({
a: undefined,
b: undefined,
c: undefined,
d: undefined,
e: 'options.controllers.bar.hover.sub',
f: 'options.hover.sub',
x: undefined,
y: undefined,
z: undefined
});
});
it('should fallback to specific scope', function() {
const defaults = {
hover: {
_fallback: 'hover',
a: 'defaults.hover'
},
controllers: {
y: 'defaults.controllers',
bar: {
z: 'defaults.controllers.bar',
hover: {
b: 'defaults.controllers.bar.hover'
}
}
},
x: 'defaults root'
};
const options = {
x: 'options',
hover: {
c: 'options.hover',
sub: {
f: 'options.hover.sub'
}
},
controllers: {
y: 'options.controllers',
bar: {
z: 'options.controllers.bar',
hover: {
d: 'options.controllers.bar.hover',
sub: {
e: 'options.controllers.bar.hover.sub'
}
}
}
}
};
const resolver = _createResolver([options, options.controllers.bar, options.controllers, defaults.controllers.bar, defaults.controllers, defaults]);
expect(resolver.hover).toEqualOptions({
a: 'defaults.hover',
b: 'defaults.controllers.bar.hover',
c: 'options.hover',
d: 'options.controllers.bar.hover',
e: undefined,
f: undefined,
x: undefined,
y: undefined,
z: undefined
});
expect(resolver.hover.sub).toEqualOptions({
a: 'defaults.hover',
b: 'defaults.controllers.bar.hover',
c: 'options.hover',
d: 'options.controllers.bar.hover',
e: 'options.controllers.bar.hover.sub',
f: 'options.hover.sub',
x: undefined,
y: undefined,
z: undefined
});
});
it('should fallback through multiple routes', function() {
const descriptors = {
_fallback: 'level1',
level1: {
_fallback: 'root'
},
level2: {
_fallback: 'level1'
}
};
const defaults = {
root: {
a: 'root'
},
level1: {
b: 'level1',
},
level2: {
level1: {
g: 'level2.level1'
},
c: 'level2',
sublevel1: {
d: 'sublevel1'
},
sublevel2: {
e: 'sublevel2',
level1: {
f: 'sublevel2.level1'
}
}
}
};
const resolver = _createResolver([defaults, descriptors]);
expect(resolver.level1).toEqualOptions({
a: 'root',
b: 'level1',
c: undefined
});
expect(resolver.level2).toEqualOptions({
a: 'root',
b: 'level1',
c: 'level2',
d: undefined
});
expect(resolver.level2.sublevel1).toEqualOptions({
a: 'root',
b: 'level1',
c: undefined,
d: 'sublevel1',
e: undefined,
f: undefined,
g: 'level2.level1'
});
expect(resolver.level2.sublevel2).toEqualOptions({
a: 'root',
b: 'level1',
c: undefined,
d: undefined,
e: 'sublevel2',
f: undefined,
g: 'level2.level1'
});
expect(resolver.level2.sublevel2.level1).toEqualOptions({
a: 'root',
b: 'level1',
c: undefined,
d: undefined,
e: undefined,
f: 'sublevel2.level1',
g: undefined // same key only included from immediate parents and root
});
});
it('should fallback through multiple routes (animations)', function() {
const descriptors = {
animations: {
_fallback: 'animation',
},
};
const defaults = {
animation: {
duration: 1000,
easing: 'easeInQuad'
},
animations: {
colors: {
properties: ['color', 'backgroundColor'],
type: 'color'
},
numbers: {
properties: ['x', 'y'],
type: 'number'
}
},
transitions: {
resize: {
animation: {
duration: 0
}
},
show: {
animation: {
duration: 400
},
animations: {
colors: {
from: 'transparent'
}
}
}
}
};
const options = {
animation: {
easing: 'linear'
},
animations: {
colors: {
properties: ['color', 'borderColor', 'backgroundColor'],
},
duration: {
properties: ['a', 'b'],
type: 'boolean'
}
}
};
const show = _createResolver([options, defaults.transitions.show, defaults, descriptors]);
expect(show.animation).toEqualOptions({
duration: 400,
easing: 'linear'
});
expect(show.animations.colors._scopes).toEqual([
options.animations.colors,
defaults.transitions.show.animations.colors,
defaults.animations.colors,
options.animation,
defaults.transitions.show.animation,
defaults.animation
]);
expect(show.animations.colors).toEqualOptions({
duration: 400,
from: 'transparent',
easing: 'linear',
type: 'color',
properties: ['color', 'borderColor', 'backgroundColor']
});
expect(show.animations.duration).toEqualOptions({
duration: 400,
easing: 'linear',
type: 'boolean',
properties: ['a', 'b']
});
expect(Object.getOwnPropertyNames(show.animations).filter(k => Chart.helpers.isObject(show.animations[k]))).toEqual([
'colors',
'duration',
'numbers',
]);
const def = _createResolver([options, defaults, descriptors]);
expect(def.animation).toEqualOptions({
duration: 1000,
easing: 'linear'
});
expect(def.animations.colors._scopes).toEqual([
options.animations.colors,
defaults.animations.colors,
options.animation,
defaults.animation
]);
expect(def.animations.colors).toEqualOptions({
duration: 1000,
easing: 'linear',
type: 'color',
properties: ['color', 'borderColor', 'backgroundColor']
});
expect(def.animations.duration).toEqualOptions({
duration: 1000,
easing: 'linear',
type: 'boolean',
properties: ['a', 'b']
});
expect(Object.getOwnPropertyNames(def.animations).filter(k => Chart.helpers.isObject(show.animations[k]))).toEqual([
'colors',
'duration',
'numbers',
]);
});
});
describe('setting values', function() {
it('should set values to first scope', function() {
const defaults = {
value: true
};
const options = {};
const resolver = _createResolver([options, defaults]);
resolver.value = false;
expect(options.value).toBeFalse();
expect(defaults.value).toBeTrue();
expect(resolver.value).toBeFalse();
});
it('should set values of sub-objects to first scope', function() {
const defaults = {
sub: {
value: true
}
};
const options = {};
const resolver = _createResolver([options, defaults]);
resolver.sub.value = false;
expect(options.sub.value).toBeFalse();
expect(defaults.sub.value).toBeTrue();
expect(resolver.sub.value).toBeFalse();
});
it('should throw when setting a value and options is frozen', function() {
const defaults = Object.freeze({default: true});
const options = Object.freeze({value: true});
const resolver = _createResolver([options, defaults]);
function set() {
resolver.value = false;
}
expect(set).toThrow();
});
});
});
describe('_attachContext', function() {
it('should resolve to final values', function() {
const defaults = {
color: 'red',
backgroundColor: 'green',
hoverColor: (ctx, options) => getHoverColor(options.color)
};
const options = {
color: ['white', 'blue']
};
const resolver = _createResolver([options, defaults]);
const opts = _attachContext(resolver, {index: 1});
expect(opts.color).toEqual('blue');
expect(opts.backgroundColor).toEqual('green');
expect(opts.hoverColor).toEqual(getHoverColor('blue'));
});
it('should thrown on recursion', function() {
const options = {
foo: (ctx, opts) => opts.bar,
bar: (ctx, opts) => opts.xyz,
xyz: (ctx, opts) => opts.foo
};
const resolver = _createResolver([options]);
const opts = _attachContext(resolver, {test: true});
expect(function() {
return opts.foo;
}).toThrowError('Recursion detected: foo->bar->xyz->foo');
});
it('should support scriptable options in subscopes', function() {
const defaults = {
elements: {
point: {
backgroundColor: 'red'
}
}
};
const options = {
elements: {
point: {
borderColor: (ctx, opts) => getHoverColor(opts.backgroundColor)
}
}
};
const resolver = _createResolver([options, defaults]);
const opts = _attachContext(resolver, {});
expect(opts.elements.point.borderColor).toEqual(getHoverColor('red'));
expect(opts.elements.point.backgroundColor).toEqual('red');
});
it('same resolver should be usable with multiple contexts', function() {
const defaults = {
animation: {
delay: 10
}
};
const options = {
animation: (ctx) => ctx.index === 0 ? {duration: 1000} : {duration: 500}
};
const resolver = _createResolver([options, defaults]);
const opts1 = _attachContext(resolver, {index: 0});
const opts2 = _attachContext(resolver, {index: 1});
expect(opts1.animation.duration).toEqual(1000);
expect(opts1.animation.delay).toEqual(10);
expect(opts2.animation.duration).toEqual(500);
expect(opts2.animation.delay).toEqual(10);
});
it('should fall back from object returned from scriptable option', function() {
const defaults = {
mainScope: {
main: true,
subScope: {
sub: true
}
}
};
const options = {
mainScope: (ctx) => ({
mainTest: ctx.contextValue,
subScope: {
subText: 'a'
}
})
};
const opts = _attachContext(_createResolver([options, defaults]), {contextValue: 'test'});
expect(opts.mainScope).toEqualOptions({
main: true,
mainTest: 'test',
subScope: {
sub: true,
subText: 'a'
}
});
});
it('should resolve array of non-indexable objects properly', function() {
const defaults = {
label: {
value: 42,
text: (ctx) => ctx.text
},
labels: {
_fallback: 'label',
_indexable: false
}
};
const options = {
labels: [{text: 'a'}, {text: 'b'}, {value: 1}]
};
const opts = _attachContext(_createResolver([options, defaults]), {text: 'context'});
expect(opts).toEqualOptions({
labels: [
{
text: 'a',
value: 42
},
{
text: 'b',
value: 42
},
{
text: 'context',
value: 1
}
]
});
});
it('should call _fallback with proper value from array when descriptor is object', function() {
const spy = jasmine.createSpy('fallback');
const descriptors = {
items: {
_fallback: spy
}
};
const options = {
items: [{test: true}]
};
const resolver = _createResolver([options, descriptors]);
const opts = _attachContext(resolver, {dymmy: true});
const item0 = opts.items[0];
expect(item0.test).toEqual(true);
expect(spy).toHaveBeenCalledWith('items', options.items[0]);
});
it('should call _fallback with proper value from array when descriptor and defaults are objects', function() {
const spy = jasmine.createSpy('fallback');
const descriptors = {
items: {
_fallback: spy
}
};
const defaults = {
items: {
type: 'defaultType'
}
};
const options = {
items: [{test: true}]
};
const resolver = _createResolver([options, defaults, descriptors]);
const opts = _attachContext(resolver, {dymmy: true});
const item0 = opts.items[0];
expect(item0.test).toEqual(true);
expect(spy).toHaveBeenCalledWith('items', options.items[0]);
});
it('should support overriding options', function() {
const options = {
fn1: ctx => ctx.index,
fn2: ctx => ctx.type
};
const override = {
fn1: ctx => ctx.index * 2
};
const opts = _attachContext(_createResolver([options]), {index: 2, type: 'test'});
expect(opts).toEqualOptions({
fn1: 2,
fn2: 'test'
});
expect(opts.override(override)).toEqualOptions({
fn1: 4,
fn2: 'test'
});
});
it('should support changing context', function() {
const opts = _attachContext(_createResolver([{fn: ctx => ctx.test}]), {test: 1});
expect(opts.fn).toEqual(1);
expect(opts.setContext({test: 2}).fn).toEqual(2);
expect(opts.fn).toEqual(1);
});
it('should support common object methods', function() {
const defaults = {
option1: 'defaults'
};
class Options {
constructor() {
this.option2 = () => 'options';
}
get getter() {
return 'options getter';
}
}
const options = new Options();
const resolver = _createResolver([options, defaults]);
const opts = _attachContext(resolver, {index: 1});
expect(Object.prototype.hasOwnProperty.call(opts, 'option2')).toBeTrue();
expect(Object.prototype.hasOwnProperty.call(opts, 'option1')).toBeFalse();
expect(Object.prototype.hasOwnProperty.call(opts, 'getter')).toBeFalse();
expect(Object.prototype.hasOwnProperty.call(opts, 'nonexistent')).toBeFalse();
expect(Object.keys(opts)).toEqual(['option2']);
expect(Object.getOwnPropertyNames(opts)).toEqual(['option2', 'option1']);
expect('option2' in opts).toBeTrue();
expect('option1' in opts).toBeTrue();
expect('getter' in opts).toBeFalse();
expect('nonexistent' in opts).toBeFalse();
expect(opts instanceof Options).toBeTrue();
expect(opts.getter).toEqual('options getter');
expect('test' in opts).toBeFalse();
expect(opts.test).toBeUndefined();
opts.test = true;
expect('test' in opts).toBeTrue();
expect(opts.test).toBeTrue();
delete opts.test;
expect('test' in opts).toBeFalse();
opts.test = (ctx) => ctx.index;
expect('test' in opts).toBeTrue();
expect(opts.test).toBe(1);
delete opts.test;
expect('test' in opts).toBeFalse();
});
it('should not create proxy for adapters', function() {
const defaults = {
scales: {
time: {
adapters: {
date: {
locale: {
method: (arg) => arg === undefined ? 'ok' : 'fail'
}
}
}
}
}
};
const resolver = _createResolver([{}, defaults]);
const opts = _attachContext(resolver, {index: 1});
const fn = opts.scales.time.adapters.date.locale.method;
expect(typeof fn).toBe('function');
expect(fn()).toEqual('ok');
});
it('should not create proxy for objects with custom constructor', function() {
class MyClass {
constructor() {
this.string = 'test string';
}
method(arg) {
return arg === undefined ? 'ok' : 'fail';
}
}
const defaults = {
test: new MyClass()
};
const resolver = _createResolver([{}, defaults]);
const opts = _attachContext(resolver, {index: 1});
const fn = opts.test.method;
expect(typeof fn).toBe('function');
expect(fn()).toEqual('ok');
expect(opts.test.string).toEqual('test string');
expect(opts.test.constructor).toEqual(MyClass);
});
it('should properly set value to object in array of objects', function() {
const defaults = {};
const options = {
annotations: [{
value: 10
}, {
value: 20
}]
};
const resolver = _attachContext(_createResolver([options, defaults]), {test: true});
expect(resolver.annotations[0].value).toEqual(10);
resolver.annotations[0].value = 15;
expect(options.annotations[0].value).toEqual(15);
expect(options.annotations[1].value).toEqual(20);
});
describe('_indexable and _scriptable', function() {
it('should default to true', function() {
const options = {
array: [1, 2, 3],
func: (ctx) => ctx.index * 10
};
const opts = _attachContext(_createResolver([options]), {index: 1});
expect(opts.array).toEqual(2);
expect(opts.func).toEqual(10);
});
it('should allow false', function() {
const fn = () => 'test';
const options = {
_indexable: false,
_scriptable: false,
array: [1, 2, 3],
func: fn
};
const opts = _attachContext(_createResolver([options]), {index: 1});
expect(opts.array).toEqual([1, 2, 3]);
expect(opts.func).toEqual(fn);
expect(opts.func()).toEqual('test');
});
it('should allow function', function() {
const fn = () => 'test';
const options = {
_indexable: (prop) => prop !== 'array',
_scriptable: (prop) => prop === 'func',
array: [1, 2, 3],
array2: ['a', 'b', 'c'],
func: fn
};
const opts = _attachContext(_createResolver([options]), {index: 1});
expect(opts.array).toEqual([1, 2, 3]);
expect(opts.func).toEqual('test');
expect(opts.array2).toEqual('b');
});
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/element.arc.tests.js | test/specs/element.arc.tests.js | // Test the rectangle element
describe('Arc element tests', function() {
it ('should determine if in range', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI / 2,
x: 0,
y: 0,
innerRadius: 5,
outerRadius: 10,
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
expect(arc.inRange(2, 2)).toBe(false);
expect(arc.inRange(7, 0)).toBe(true);
expect(arc.inRange(0, 11)).toBe(false);
expect(arc.inRange(Math.sqrt(32), Math.sqrt(32))).toBe(true);
expect(arc.inRange(-1.0 * Math.sqrt(7), Math.sqrt(7))).toBe(false);
});
it ('should determine if in range when full circle', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI * 2,
x: 0,
y: 0,
innerRadius: 5,
outerRadius: 10,
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
for (const radius of [5, 7.5, 10]) {
for (let angle = 0; angle <= 360; angle += 22.5) {
const rad = angle / 180 * Math.PI;
const x = Math.sin(rad) * radius;
const y = Math.cos(rad) * radius;
expect(arc.inRange(x, y)).withContext(`radius: ${radius}, angle: ${angle}`).toBeTrue();
}
}
for (const radius of [4, 11]) {
for (let angle = 0; angle <= 360; angle += 22.5) {
const rad = angle / 180 * Math.PI;
const x = Math.sin(rad) * radius;
const y = Math.cos(rad) * radius;
expect(arc.inRange(x, y)).withContext(`radius: ${radius}, angle: ${angle}`).toBeFalse();
}
}
});
it ('should include spacing for in range check', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI / 2,
x: 0,
y: 0,
innerRadius: 5,
outerRadius: 10,
options: {
spacing: 10,
offset: 0,
borderWidth: 0
}
});
expect(arc.inRange(7, 0)).toBe(false);
expect(arc.inRange(15, 0)).toBe(true);
});
it ('should include borderWidth for in range check', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI / 2,
x: 0,
y: 0,
innerRadius: 5,
outerRadius: 10,
options: {
spacing: 0,
offset: 0,
borderWidth: 10
}
});
expect(arc.inRange(7, 0)).toBe(false);
expect(arc.inRange(15, 0)).toBe(true);
});
it ('should determine if in range, when full circle', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: -Math.PI,
endAngle: Math.PI * 1.5,
x: 0,
y: 0,
innerRadius: 0,
outerRadius: 10,
circumference: Math.PI * 2,
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
expect(arc.inRange(7, 7)).toBe(true);
});
it ('should get the tooltip position', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI / 2,
x: 0,
y: 0,
innerRadius: 0,
outerRadius: Math.sqrt(2),
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
var pos = arc.tooltipPosition();
expect(pos.x).toBeCloseTo(0.5);
expect(pos.y).toBeCloseTo(0.5);
});
it ('should get the center', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI / 2,
x: 0,
y: 0,
innerRadius: 0,
outerRadius: Math.sqrt(2),
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
var center = arc.getCenterPoint();
expect(center.x).toBeCloseTo(0.5, 6);
expect(center.y).toBeCloseTo(0.5, 6);
});
it ('should get the center with offset and spacing', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI / 2,
x: 0,
y: 0,
innerRadius: 0,
outerRadius: Math.sqrt(2),
options: {
spacing: 10,
offset: 10,
borderWidth: 0
}
});
var center = arc.getCenterPoint();
expect(center.x).toBeCloseTo(7.57, 1);
expect(center.y).toBeCloseTo(7.57, 1);
});
it ('should get the center of full circle before and after draw', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI * 2,
x: 2,
y: 2,
innerRadius: 0,
outerRadius: 2,
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
var center = arc.getCenterPoint();
expect(center.x).toBeCloseTo(1, 6);
expect(center.y).toBeCloseTo(2, 6);
var ctx = window.createMockContext();
arc.draw(ctx);
center = arc.getCenterPoint();
expect(center.x).toBeCloseTo(1, 6);
expect(center.y).toBeCloseTo(2, 6);
});
it('should not draw when radius < 0', function() {
var ctx = window.createMockContext();
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI / 2,
x: 0,
y: 0,
innerRadius: -0.1,
outerRadius: Math.sqrt(2),
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
arc.draw(ctx);
expect(ctx.getCalls().length).toBe(0);
arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI / 2,
x: 0,
y: 0,
innerRadius: 0,
outerRadius: -1,
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
arc.draw(ctx);
expect(ctx.getCalls().length).toBe(0);
});
it('should draw when circular: false', function() {
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: Math.PI * 2,
x: 2,
y: 2,
innerRadius: 0,
outerRadius: 2,
options: {
spacing: 0,
offset: 0,
borderWidth: 0,
scales: {
r: {
grid: {
circular: false,
},
},
},
elements: {
arc: {
circular: false
},
},
}
});
var ctx = window.createMockContext();
arc.draw(ctx);
expect(ctx.getCalls().length).toBeGreaterThan(0);
});
it ('should determine not in range when angle 0', function() {
// Mock out the arc as if the controller put it there
var arc = new Chart.elements.ArcElement({
startAngle: 0,
endAngle: 0,
x: 0,
y: 0,
innerRadius: 0,
outerRadius: 10,
circumference: 0,
options: {
spacing: 0,
offset: 0,
borderWidth: 0
}
});
var center = arc.getCenterPoint();
expect(arc.inRange(center.x, 1)).toBe(false);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/scale.logarithmic.tests.js | test/specs/scale.logarithmic.tests.js | function getLabels(scale) {
return scale.ticks.map(t => t.label);
}
describe('Logarithmic Scale tests', function() {
describe('auto', jasmine.fixture.specs('scale.logarithmic'));
it('should register', function() {
var Constructor = Chart.registry.getScale('logarithmic');
expect(Constructor).not.toBe(undefined);
expect(typeof Constructor).toBe('function');
});
it('should have the correct default config', function() {
var defaultConfig = Chart.defaults.scales.logarithmic;
expect(defaultConfig).toEqual({
ticks: {
callback: Chart.Ticks.formatters.logarithmic,
major: {
enabled: true
}
}
});
// Is this actually a function
expect(defaultConfig.ticks.callback).toEqual(jasmine.any(Function));
});
it('should correctly determine the max & min data values', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [42, 1000, 64, 100],
}, {
yAxisID: 'y1',
data: [10, 5, 5000, 78, 450]
}, {
yAxisID: 'y1',
data: [150]
}, {
yAxisID: 'y2',
data: [20, 0, 150, 1800, 3040]
}, {
yAxisID: 'y3',
data: [67, 0.0004, 0, 820, 0.001]
}],
labels: ['a', 'b', 'c', 'd', 'e']
},
options: {
scales: {
y: {
id: 'y',
type: 'logarithmic'
},
y1: {
type: 'logarithmic',
position: 'right'
},
y2: {
type: 'logarithmic',
position: 'right'
},
y3: {
position: 'right',
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(10);
expect(chart.scales.y.max).toBe(1000);
expect(chart.scales.y1).not.toEqual(undefined); // must construct
expect(chart.scales.y1.min).toBe(1);
expect(chart.scales.y1.max).toBe(5000);
expect(chart.scales.y2).not.toEqual(undefined); // must construct
expect(chart.scales.y2.min).toBe(10);
expect(chart.scales.y2.max).toBe(4000);
expect(chart.scales.y3).not.toEqual(undefined); // must construct
expect(chart.scales.y3.min).toBeCloseTo(0.0001, 4);
expect(chart.scales.y3.max).toBe(900);
});
it('should correctly determine the max & min of string data values', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
yAxisID: 'y',
data: ['42', '1000', '64', '100'],
}, {
yAxisID: 'y1',
data: ['10', '5', '5000', '78', '450']
}, {
yAxisID: 'y1',
data: ['150']
}, {
yAxisID: 'y2',
data: ['20', '0', '150', '1800', '3040']
}, {
yAxisID: 'y3',
data: ['67', '0.0004', '0', '820', '0.001']
}],
labels: ['a', 'b', 'c', 'd', 'e']
},
options: {
scales: {
y: {
type: 'logarithmic'
},
y1: {
position: 'right',
type: 'logarithmic'
},
y2: {
position: 'right',
type: 'logarithmic'
},
y3: {
position: 'right',
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(40);
expect(chart.scales.y.max).toBe(1000);
expect(chart.scales.y1).not.toEqual(undefined); // must construct
expect(chart.scales.y1.min).toBe(5);
expect(chart.scales.y1.max).toBe(5000);
expect(chart.scales.y2).not.toEqual(undefined); // must construct
expect(chart.scales.y2.min).toBe(10);
expect(chart.scales.y2.max).toBe(4000);
expect(chart.scales.y3).not.toEqual(undefined); // must construct
expect(chart.scales.y3.min).toBeCloseTo(0.0001, 4);
expect(chart.scales.y3.max).toBe(900);
});
it('should correctly determine the max & min data values when there are hidden datasets', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
yAxisID: 'y1',
data: [10, 5, 5000, 78, 450]
}, {
yAxisID: 'y',
data: [42, 1000, 64, 100],
}, {
yAxisID: 'y1',
data: [50000],
hidden: true
}, {
yAxisID: 'y2',
data: [20, 0, 7400, 14, 291]
}, {
yAxisID: 'y2',
data: [6, 0.0007, 9, 890, 60000],
hidden: true
}],
labels: ['a', 'b', 'c', 'd', 'e']
},
options: {
scales: {
y: {
type: 'logarithmic'
},
y1: {
position: 'right',
type: 'logarithmic'
},
y2: {
position: 'right',
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y1).not.toEqual(undefined); // must construct
expect(chart.scales.y1.min).toBe(5);
expect(chart.scales.y1.max).toBe(5000);
expect(chart.scales.y2).not.toEqual(undefined); // must construct
expect(chart.scales.y2.min).toBe(10);
expect(chart.scales.y2.max).toBe(8000);
});
it('should correctly determine the max & min data values when there is NaN data', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [undefined, 10, null, 5, 5000, NaN, 78, 450]
}, {
yAxisID: 'y',
data: [undefined, 28, null, 1000, 500, NaN, 50, 42, Infinity, -Infinity]
}, {
yAxisID: 'y1',
data: [undefined, 30, null, 9400, 0, NaN, 54, 836]
}, {
yAxisID: 'y1',
data: [undefined, 0, null, 800, 9, NaN, 894, 21]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
},
options: {
scales: {
y: {
type: 'logarithmic'
},
y1: {
position: 'right',
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(1);
expect(chart.scales.y.max).toBe(5000);
// Turn on stacked mode since it uses it's own
chart.options.scales.y.stacked = true;
chart.update();
expect(chart.scales.y.min).toBe(1);
expect(chart.scales.y.max).toBe(6000);
expect(chart.scales.y1).not.toEqual(undefined); // must construct
expect(chart.scales.y1.min).toBe(1);
expect(chart.scales.y1.max).toBe(10000);
});
it('should correctly determine the max & min for scatter data', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [
{x: 10, y: 100},
{x: 2, y: 6},
{x: 65, y: 121},
{x: 99, y: 7}
]
}]
},
options: {
scales: {
x: {
type: 'logarithmic',
position: 'bottom'
},
y: {
type: 'logarithmic'
}
}
}
});
expect(chart.scales.x.min).toBe(2);
expect(chart.scales.x.max).toBe(100);
expect(chart.scales.y.min).toBe(6);
expect(chart.scales.y.max).toBe(150);
});
it('should correctly determine the max & min for scatter data when 0 values are present', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [
{x: 7, y: 950},
{x: 289, y: 0},
{x: 0, y: 8},
{x: 23, y: 0.04}
]
}]
},
options: {
scales: {
x: {
type: 'logarithmic',
position: 'bottom'
},
y: {
type: 'logarithmic'
}
}
}
});
expect(chart.scales.x.min).toBe(1);
expect(chart.scales.x.max).toBe(30);
expect(chart.scales.y.min).toBe(0.01);
expect(chart.scales.y.max).toBe(1000);
});
it('should correctly determine the min and max data values when stacked mode is turned on', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
type: 'bar',
yAxisID: 'y',
data: [10, 5, 1, 5, 78, 100]
}, {
yAxisID: 'y1',
data: [0, 1000],
}, {
type: 'bar',
yAxisID: 'y',
data: [150, 10, 10, 100, 10, 9]
}, {
type: 'line',
yAxisID: 'y',
data: [100, 100, 100, 100, 100, 100]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'logarithmic',
stacked: true
},
y1: {
position: 'right',
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y.min).toBe(0.1);
expect(chart.scales.y.max).toBe(200);
});
it('should correctly determine the min and max data values when stacked mode is turned on ignoring hidden datasets', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 1, 5, 78, 100],
type: 'bar'
}, {
yAxisID: 'y1',
data: [0, 1000],
type: 'bar'
}, {
yAxisID: 'y',
data: [150, 10, 10, 100, 10, 9],
type: 'bar'
}, {
yAxisID: 'y',
data: [10000, 10000, 10000, 10000, 10000, 10000],
hidden: true,
type: 'bar'
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'logarithmic',
stacked: true
},
y1: {
position: 'right',
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y.min).toBe(0.1);
expect(chart.scales.y.max).toBe(200);
});
it('should ensure that the scale has a max and min that are not equal', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: []
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y.min).toBe(1);
expect(chart.scales.y.max).toBe(10);
chart.data.datasets[0].data = [0.15, 0.15];
chart.update();
expect(chart.scales.y.min).toBe(0.1);
expect(chart.scales.y.max).toBe(0.15);
});
it('should use the min and max options', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 1, 1, 2, 1, 0]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic',
min: 10,
max: 1010,
ticks: {
callback: function(value) {
return value;
}
}
}
}
}
});
var yScale = chart.scales.y;
var tickCount = yScale.ticks.length;
expect(yScale.min).toBe(10);
expect(yScale.max).toBe(1010);
expect(yScale.ticks[0].value).toBe(10);
expect(yScale.ticks[tickCount - 1].value).toBe(1010);
});
it('should ignore negative min and max options', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 1, 1, 2, 1, 0]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic',
min: -10,
max: -1010,
ticks: {
callback: function(value) {
return value;
}
}
}
}
}
});
var y = chart.scales.y;
expect(y.min).toBe(0.1);
expect(y.max).toBe(2);
});
it('should ignore invalid min and max options', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [1, 1, 1, 2, 1, 0]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'logarithmic',
min: 'zero',
max: null,
ticks: {
callback: function(value) {
return value;
}
}
}
}
}
});
var y = chart.scales.y;
expect(y.min).toBe(0.1);
expect(y.max).toBe(2);
});
it('should generate tick marks', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [10, 5, 2, 25, 78]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic',
ticks: {
autoSkip: false,
callback: function(value) {
return value;
}
}
}
}
}
});
var scale = chart.scales.y;
expect(getLabels(scale)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 40, 50, 60, 70, 80]);
expect(scale.start).toEqual(1);
expect(scale.end).toEqual(80);
});
it('should generate tick marks when 0 values are present', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [11, 0.8, 0, 28, 7]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic',
ticks: {
callback: function(value) {
return value;
}
}
}
}
}
});
var scale = chart.scales.y;
// Counts down because the lines are drawn top to bottom
expect(getLabels(scale)).toEqual([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.5, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30]);
expect(scale.start).toEqual(0.1);
expect(scale.end).toEqual(30);
});
it('should generate tick marks in the correct order in reversed mode', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 5, 1, 25, 78]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic',
reverse: true,
ticks: {
autoSkip: false,
callback: function(value) {
return value;
}
}
}
}
}
});
var scale = chart.scales.y;
expect(getLabels(scale)).toEqual([80, 70, 60, 50, 40, 30, 20, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
expect(scale.start).toEqual(80);
expect(scale.end).toEqual(1);
});
it('should generate tick marks in the correct order in reversed mode when 0 values are present', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [21, 9, 0, 10, 25]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic',
reverse: true,
ticks: {
callback: function(value) {
return value;
}
}
}
}
}
});
var scale = chart.scales.y;
expect(getLabels(scale)).toEqual([30, 20, 15, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
expect(scale.start).toEqual(30);
expect(scale.end).toEqual(1);
});
it('should build labels using the default template', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 5, 1.1, 25, 0, 78]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic',
ticks: {
autoSkip: false
}
}
}
}
});
expect(getLabels(chart.scales.y)).toEqual(['1', '2', '3', '', '5', '', '', '', '', '10', '15', '20', '30', '', '50', '60', '70', '80']);
});
it('should build labels using the user supplied callback', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [10, 5, 2, 25, 78]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic',
ticks: {
callback: function(value, index) {
return index.toString();
}
}
}
}
}
});
// Just the index
expect(getLabels(chart.scales.y)).toEqual(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17']);
});
it('should correctly get the correct label for a data item', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 5000, 78, 450]
}, {
yAxisID: 'y1',
data: [1, 1000, 10, 100],
}, {
yAxisID: 'y',
data: [150]
}],
labels: []
},
options: {
scales: {
y: {
type: 'logarithmic'
},
y1: {
position: 'right',
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y.getLabelForValue(150)).toBe('150');
});
it('should correctly use the locale when generating the label', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 5000, 78, 450]
}, {
yAxisID: 'y1',
data: [1, 1000, 10, 100],
}, {
yAxisID: 'y',
data: [150]
}],
labels: []
},
options: {
locale: 'de-DE',
scales: {
y: {
type: 'logarithmic'
},
y1: {
position: 'right',
type: 'logarithmic'
}
}
}
});
expect(chart.scales.y.getLabelForValue(10.25)).toBe('10,25');
});
describe('when', function() {
var data = [
{
data: [1, 39],
stack: 'stack'
},
{
data: [1, 39],
stack: 'stack'
},
];
var dataWithEmptyStacks = [
{
data: []
},
{
data: []
}
].concat(data);
var config = [
{
axis: 'y',
firstTick: 1, // start of the axis (minimum)
describe: 'all stacks are defined'
},
{
axis: 'y',
data: dataWithEmptyStacks,
firstTick: 1,
describe: 'not all stacks are defined'
},
{
axis: 'y',
scale: {
y: {
min: 0
}
},
firstTick: 0.1,
describe: 'all stacks are defined and min: 0'
},
{
axis: 'y',
data: dataWithEmptyStacks,
scale: {
y: {
min: 0
}
},
firstTick: 0.1,
describe: 'not stacks are defined and min: 0'
},
{
axis: 'x',
firstTick: 1,
describe: 'all stacks are defined'
},
{
axis: 'x',
data: dataWithEmptyStacks,
firstTick: 1,
describe: 'not all stacks are defined'
},
{
axis: 'x',
scale: {
x: {
min: 0
}
},
firstTick: 0.1,
describe: 'all stacks are defined and min: 0'
},
{
axis: 'x',
data: dataWithEmptyStacks,
scale: {
x: {
min: 0
}
},
firstTick: 0.1,
describe: 'not all stacks are defined and min: 0'
},
];
config.forEach(function(setup) {
var scaleConfig = {};
var indexAxis, chartStart, chartEnd;
if (setup.axis === 'x') {
indexAxis = 'y';
chartStart = 'left';
chartEnd = 'right';
} else {
indexAxis = 'x';
chartStart = 'bottom';
chartEnd = 'top';
}
scaleConfig[setup.axis] = {
type: 'logarithmic',
beginAtZero: false
};
Object.assign(scaleConfig, setup.scale);
scaleConfig[setup.axis].type = 'logarithmic';
var description = 'dataset has stack option and ' + setup.describe
+ ' and axis is "' + setup.axis + '";';
describe(description, function() {
it('should define the correct axis limits', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
labels: ['category 1', 'category 2'],
datasets: setup.data || data,
},
options: {
indexAxis,
scales: scaleConfig
}
});
var axisID = setup.axis;
var scale = chart.scales[axisID];
var firstTick = setup.firstTick;
var lastTick = 80; // last tick (should be first available tick after: 2 * 39)
var start = chart.chartArea[chartStart];
var end = chart.chartArea[chartEnd];
expect(scale.getPixelForValue(firstTick)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(lastTick)).toBeCloseToPixel(end);
expect(scale.getValueForPixel(start)).toBeCloseTo(firstTick, 4);
expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4);
chart.scales[axisID].options.reverse = true; // Reverse mode
chart.update();
// chartArea might have been resized in update
start = chart.chartArea[chartEnd];
end = chart.chartArea[chartStart];
expect(scale.getPixelForValue(firstTick)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(lastTick)).toBeCloseToPixel(end);
expect(scale.getValueForPixel(start)).toBeCloseTo(firstTick, 4);
expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4);
});
});
});
});
describe('when', function() {
var config = [
{
dataset: [],
firstTick: 1, // value of the first tick
lastTick: 10, // value of the last tick
describe: 'empty dataset, without min/max'
},
{
dataset: [],
scale: {stacked: true},
firstTick: 1,
lastTick: 10,
describe: 'empty dataset, without min/max, with stacked: true'
},
{
data: {
datasets: [
{data: [], stack: 'stack'},
{data: [], stack: 'stack'},
],
},
type: 'bar',
firstTick: 1,
lastTick: 10,
describe: 'empty dataset with stack option, without min/max'
},
{
dataset: [],
scale: {min: 1},
firstTick: 1,
lastTick: 10,
describe: 'empty dataset, min: 1, without max'
},
{
dataset: [],
scale: {max: 80},
firstTick: 1,
lastTick: 80,
describe: 'empty dataset, max: 80, without min'
},
{
dataset: [],
scale: {max: 0.8},
firstTick: 0.01,
lastTick: 0.8,
describe: 'empty dataset, max: 0.8, without min'
},
{
dataset: [{x: 10, y: 10}, {x: 5, y: 5}, {x: 1, y: 1}, {x: 25, y: 25}, {x: 78, y: 78}],
firstTick: 1,
lastTick: 80,
describe: 'dataset min point {x: 1, y: 1}, max point {x:78, y:78}'
},
];
config.forEach(function(setup) {
var axes = [
{
id: 'x', // horizontal scale
start: 'left',
end: 'right'
},
{
id: 'y', // vertical scale
start: 'bottom',
end: 'top'
}
];
axes.forEach(function(axis) {
var expectation = 'min = ' + setup.firstTick + ', max = ' + setup.lastTick;
describe(setup.describe + ' and axis is "' + axis.id + '"; expect: ' + expectation + ';', function() {
beforeEach(function() {
var xConfig = {
type: 'logarithmic',
position: 'bottom'
};
var yConfig = {
type: 'logarithmic',
position: 'left'
};
var data = setup.data || {
datasets: [{
data: setup.dataset
}],
};
Object.assign(xConfig, setup.scale);
Object.assign(yConfig, setup.scale);
Object.assign(data, setup.data || {});
this.chart = window.acquireChart({
type: 'line',
data: data,
options: {
scales: {
x: xConfig,
y: yConfig
}
}
});
});
it('should get the correct pixel value for a point', function() {
var chart = this.chart;
var axisID = axis.id;
var scale = chart.scales[axisID];
var firstTick = setup.firstTick;
var lastTick = setup.lastTick;
var start = chart.chartArea[axis.start];
var end = chart.chartArea[axis.end];
expect(scale.getPixelForValue(firstTick)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(lastTick)).toBeCloseToPixel(end);
expect(scale.getPixelForValue(0)).toBeCloseToPixel(start); // 0 is invalid, put it at the start.
expect(scale.getValueForPixel(start)).toBeCloseTo(firstTick, 4);
expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4);
chart.scales[axisID].options.reverse = true; // Reverse mode
chart.update();
// chartArea might have been resized in update
start = chart.chartArea[axis.end];
end = chart.chartArea[axis.start];
expect(scale.getPixelForValue(firstTick)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(lastTick)).toBeCloseToPixel(end);
expect(scale.getValueForPixel(start)).toBeCloseTo(firstTick, 4);
expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4);
});
});
});
});
});
describe('when', function() {
var config = [
{
dataset: [],
scale: {min: 0},
lastTick: 10, // value of the last tick
describe: 'empty dataset, min: 0, without max'
},
{
dataset: [],
scale: {min: 0, max: 80},
lastTick: 80,
describe: 'empty dataset, min: 0, max: 80'
},
{
dataset: [],
scale: {min: 0, max: 0.8},
lastTick: 0.8,
describe: 'empty dataset, min: 0, max: 0.8'
},
{
dataset: [{x: 0, y: 0}, {x: 10, y: 10}, {x: 1.2, y: 1.2}, {x: 25, y: 25}, {x: 78, y: 78}],
lastTick: 80,
describe: 'dataset min point {x: 0, y: 0}, max point {x:78, y:78}'
},
{
dataset: [{x: 0, y: 0}, {x: 10, y: 10}, {x: 6.3, y: 6.3}, {x: 25, y: 25}, {x: 78, y: 78}],
lastTick: 80,
describe: 'dataset min point {x: 0, y: 0}, max point {x:78, y:78}'
},
{
dataset: [{x: 10, y: 10}, {x: 1.2, y: 1.2}, {x: 25, y: 25}, {x: 78, y: 78}],
scale: {min: 0},
lastTick: 80,
describe: 'dataset min point {x: 1.2, y: 1.2}, max point {x:78, y:78}, min: 0'
},
{
dataset: [{x: 10, y: 10}, {x: 6.3, y: 6.3}, {x: 25, y: 25}, {x: 78, y: 78}],
scale: {min: 0},
lastTick: 80,
describe: 'dataset min point {x: 6.3, y: 6.3}, max point {x:78, y:78}, min: 0'
},
];
config.forEach(function(setup) {
var axes = [
{
id: 'x', // horizontal scale
start: 'left',
end: 'right'
},
{
id: 'y', // vertical scale
start: 'bottom',
end: 'top'
}
];
axes.forEach(function(axis) {
var expectation = 'min = 0, max = ' + setup.lastTick;
describe(setup.describe + ' and axis is "' + axis.id + '"; expect: ' + expectation + ';', function() {
beforeEach(function() {
var xConfig = {
type: 'logarithmic',
position: 'bottom'
};
var yConfig = {
type: 'logarithmic',
position: 'left'
};
var data = setup.data || {
datasets: [{
data: setup.dataset
}],
};
Object.assign(xConfig, setup.scale);
Object.assign(yConfig, setup.scale);
Object.assign(data, setup.data || {});
this.chart = window.acquireChart({
type: 'line',
data: data,
options: {
scales: {
x: xConfig,
y: yConfig
}
}
});
});
it('should get the correct pixel value for a point', function() {
var chart = this.chart;
var axisID = axis.id;
var scale = chart.scales[axisID];
var lastTick = setup.lastTick;
var start = chart.chartArea[axis.start];
var end = chart.chartArea[axis.end];
expect(scale.getPixelForValue(0)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(lastTick)).toBeCloseToPixel(end);
expect(scale.getValueForPixel(start)).toBeCloseTo(scale.min, 4);
expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4);
chart.scales[axisID].options.reverse = true; // Reverse mode
chart.update();
// chartArea might have been resized in update
start = chart.chartArea[axis.end];
end = chart.chartArea[axis.start];
expect(scale.getPixelForValue(0)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(lastTick)).toBeCloseToPixel(end);
expect(scale.getValueForPixel(start)).toBeCloseTo(scale.min, 4);
expect(scale.getValueForPixel(end)).toBeCloseTo(lastTick, 4);
});
});
});
});
});
it('Should correctly determine the max & min when no values provided and suggested minimum and maximum are set', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: []
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
},
options: {
scales: {
y: {
type: 'logarithmic',
suggestedMin: 10,
suggestedMax: 100
}
}
}
});
expect(chart.scales.y).not.toEqual(undefined); // must construct
expect(chart.scales.y.min).toBe(10);
expect(chart.scales.y.max).toBe(100);
});
it('Should bound to data', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: ['a', 'b'],
datasets: [{
data: [1.1, 99]
}]
},
options: {
scales: {
y: {
type: 'logarithmic',
bounds: 'data'
}
}
}
});
expect(chart.scales.y.min).toEqual(1.1);
expect(chart.scales.y.max).toEqual(99);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/controller.line.tests.js | test/specs/controller.line.tests.js | describe('Chart.controllers.line', function() {
describe('auto', jasmine.fixture.specs('controller.line'));
it('should be registered as dataset controller', function() {
expect(typeof Chart.controllers.line).toBe('function');
});
it('should be constructed', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: []
}],
labels: []
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.type).toBe('line');
expect(meta.controller).not.toBe(undefined);
expect(meta.controller.index).toBe(0);
expect(meta.data).toEqual([]);
meta.controller.updateIndex(1);
expect(meta.controller.index).toBe(1);
});
it('Should use the first scale IDs if the dataset does not specify them', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: []
}],
labels: []
},
});
var meta = chart.getDatasetMeta(0);
expect(meta.xAxisID).toBe('x');
expect(meta.yAxisID).toBe('y');
});
it('Should not throw with empty dataset when tension is non-zero', function() {
// https://github.com/chartjs/Chart.js/issues/8676
function createChart() {
return window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [],
tension: 0.5
}],
labels: []
},
});
}
expect(createChart).not.toThrow();
});
it('should find min and max for stacked chart', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 11, 12, 13]
}, {
data: [1, 2, 3, 4]
}],
labels: ['a', 'b', 'c', 'd']
},
options: {
scales: {
y: {
stacked: true
}
}
}
});
expect(chart.getDatasetMeta(0).controller.getMinMax(chart.scales.y, true)).toEqual({min: 10, max: 13});
expect(chart.getDatasetMeta(1).controller.getMinMax(chart.scales.y, true)).toEqual({min: 11, max: 17});
chart.hide(0);
expect(chart.getDatasetMeta(0).controller.getMinMax(chart.scales.y, true)).toEqual({min: 10, max: 13});
expect(chart.getDatasetMeta(1).controller.getMinMax(chart.scales.y, true)).toEqual({min: 1, max: 4});
});
it('Should create line elements and point elements for each data item during initialization', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset1'
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4); // 4 points created
expect(meta.data[0] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.dataset instanceof Chart.elements.LineElement).toBe(true); // 1 line element
});
it('should draw all elements', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset1'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
showLine: true
}
});
var meta = chart.getDatasetMeta(0);
spyOn(meta.dataset, 'updateControlPoints');
spyOn(meta.dataset, 'draw');
spyOn(meta.data[0], 'draw');
spyOn(meta.data[1], 'draw');
spyOn(meta.data[2], 'draw');
spyOn(meta.data[3], 'draw');
chart.update();
expect(meta.dataset.updateControlPoints.calls.count()).toBeGreaterThanOrEqual(1);
expect(meta.dataset.draw.calls.count()).toBe(1);
expect(meta.data[0].draw.calls.count()).toBe(1);
expect(meta.data[1].draw.calls.count()).toBe(1);
expect(meta.data[2].draw.calls.count()).toBe(1);
expect(meta.data[3].draw.calls.count()).toBe(1);
});
it('should update elements when modifying data', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset',
xAxisID: 'x',
yAxisID: 'y'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
showLine: true,
plugins: {
legend: false,
title: false
},
elements: {
point: {
backgroundColor: 'red',
borderColor: 'blue',
}
},
scales: {
x: {
display: false
},
y: {
display: false
}
}
},
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4);
chart.data.datasets[0].data = [1, 2]; // remove 2 items
chart.data.datasets[0].borderWidth = 1;
chart.update();
expect(meta.data.length).toBe(2);
expect(meta._parsed.length).toBe(2);
[
{x: 5, y: 507},
{x: 171, y: 5}
].forEach(function(expected, i) {
expect(meta.data[i].x).toBeCloseToPixel(expected.x);
expect(meta.data[i].y).toBeCloseToPixel(expected.y);
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
backgroundColor: 'red',
borderColor: 'blue',
}));
});
chart.data.datasets[0].data = [1, 2, 3]; // add 1 items
chart.update();
expect(meta.data.length).toBe(3); // should add a new meta data item
});
it('should correctly calculate x scale for label and point', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: ['One'],
datasets: [{
data: [1],
}]
},
options: {
plugins: {
legend: false,
title: false
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
x: {
display: false,
},
y: {
display: false,
beginAtZero: true
}
}
}
});
var meta = chart.getDatasetMeta(0);
// 1 point
var point = meta.data[0];
expect(point.x).toBeCloseToPixel(5);
// 2 points
chart.data.labels = ['One', 'Two'];
chart.data.datasets[0].data = [1, 2];
chart.update();
var points = meta.data;
expect(points[0].x).toBeCloseToPixel(5);
expect(points[1].x).toBeCloseToPixel(507);
// 3 points
chart.data.labels = ['One', 'Two', 'Three'];
chart.data.datasets[0].data = [1, 2, 3];
chart.update();
points = meta.data;
expect(points[0].x).toBeCloseToPixel(5);
expect(points[1].x).toBeCloseToPixel(256);
expect(points[2].x).toBeCloseToPixel(507);
// 4 points
chart.data.labels = ['One', 'Two', 'Three', 'Four'];
chart.data.datasets[0].data = [1, 2, 3, 4];
chart.update();
points = meta.data;
expect(points[0].x).toBeCloseToPixel(5);
expect(points[1].x).toBeCloseToPixel(171);
expect(points[2].x).toBeCloseToPixel(340);
expect(points[3].x).toBeCloseToPixel(507);
});
it('should update elements when the y scale is stacked', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, -10, 10, -10],
label: 'dataset1'
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
display: false,
},
y: {
display: false,
stacked: true
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{x: 5, y: 148},
{x: 171, y: 435},
{x: 341, y: 148},
{x: 507, y: 435}
].forEach(function(values, i) {
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{x: 5, y: 5},
{x: 171, y: 76},
{x: 341, y: 148},
{x: 507, y: 492}
].forEach(function(values, i) {
expect(meta1.data[i].x).toBeCloseToPixel(values.x);
expect(meta1.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should update elements when the y scale is stacked with multiple axes', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, -10, 10, -10],
label: 'dataset1'
}, {
data: [10, 15, 0, -4],
label: 'dataset2'
}, {
data: [10, 10, -10, -10],
label: 'dataset3',
yAxisID: 'y2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false,
},
scales: {
x: {
display: false,
},
y: {
display: false,
stacked: true
},
y2: {
type: 'linear',
position: 'right',
display: false
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{x: 5, y: 148},
{x: 171, y: 435},
{x: 341, y: 148},
{x: 507, y: 435}
].forEach(function(values, i) {
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{x: 5, y: 5},
{x: 171, y: 76},
{x: 341, y: 148},
{x: 507, y: 492}
].forEach(function(values, i) {
expect(meta1.data[i].x).toBeCloseToPixel(values.x);
expect(meta1.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should update elements when the y scale is stacked and datasets is scatter data', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [{
x: 0,
y: 10
}, {
x: 1,
y: -10
}, {
x: 2,
y: 10
}, {
x: 3,
y: -10
}],
label: 'dataset1'
}, {
data: [{
x: 0,
y: 10
}, {
x: 1,
y: 15
}, {
x: 2,
y: 0
}, {
x: 3,
y: -4
}],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
display: false,
},
y: {
display: false,
stacked: true
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{x: 5, y: 148},
{x: 171, y: 435},
{x: 341, y: 148},
{x: 507, y: 435}
].forEach(function(values, i) {
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{x: 5, y: 5},
{x: 171, y: 76},
{x: 341, y: 148},
{x: 507, y: 492}
].forEach(function(values, i) {
expect(meta1.data[i].x).toBeCloseToPixel(values.x);
expect(meta1.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should update elements when the y scale is stacked and data is strings', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: ['10', '-10', '10', '-10'],
label: 'dataset1'
}, {
data: ['10', '15', '0', '-4'],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
display: false,
},
y: {
display: false,
stacked: true
}
}
}
});
var meta0 = chart.getDatasetMeta(0);
[
{x: 5, y: 148},
{x: 171, y: 435},
{x: 341, y: 148},
{x: 507, y: 435}
].forEach(function(values, i) {
expect(meta0.data[i].x).toBeCloseToPixel(values.x);
expect(meta0.data[i].y).toBeCloseToPixel(values.y);
});
var meta1 = chart.getDatasetMeta(1);
[
{x: 5, y: 5},
{x: 171, y: 76},
{x: 341, y: 148},
{x: 507, y: 492}
].forEach(function(values, i) {
expect(meta1.data[i].x).toBeCloseToPixel(values.x);
expect(meta1.data[i].y).toBeCloseToPixel(values.y);
});
});
it('should fall back to the line styles for points', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [0, 0],
label: 'dataset1',
// line styles
backgroundColor: 'rgb(98, 98, 98)',
borderColor: 'rgb(8, 8, 8)',
borderWidth: 0.55,
}],
labels: ['label1', 'label2']
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.dataset.options.backgroundColor).toBe('rgb(98, 98, 98)');
expect(meta.dataset.options.borderColor).toBe('rgb(8, 8, 8)');
expect(meta.dataset.options.borderWidth).toBe(0.55);
});
describe('dataset global defaults', function() {
beforeEach(function() {
this._defaults = Chart.helpers.clone(Chart.defaults.datasets.line);
});
afterEach(function() {
Chart.defaults.datasets.line = this._defaults;
delete this._defaults;
});
it('should utilize the dataset global default options', function() {
Chart.helpers.merge(Chart.defaults.datasets.line, {
spanGaps: true,
tension: 0.231,
backgroundColor: '#add',
borderWidth: '#daa',
borderColor: '#dad',
borderCapStyle: 'round',
borderDash: [0],
borderDashOffset: 0.871,
borderJoinStyle: 'miter',
fill: 'start',
cubicInterpolationMode: 'monotone'
});
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [0, 0],
label: 'dataset1'
}],
labels: ['label1', 'label2']
}
});
var options = chart.getDatasetMeta(0).dataset.options;
expect(options.spanGaps).toBe(true);
expect(options.tension).toBe(0.231);
expect(options.backgroundColor).toBe('#add');
expect(options.borderWidth).toBe('#daa');
expect(options.borderColor).toBe('#dad');
expect(options.borderCapStyle).toBe('round');
expect(options.borderDash).toEqual([0]);
expect(options.borderDashOffset).toBe(0.871);
expect(options.borderJoinStyle).toBe('miter');
expect(options.fill).toBe('start');
expect(options.cubicInterpolationMode).toBe('monotone');
});
it('should be overridden by user-supplied values', function() {
Chart.helpers.merge(Chart.defaults.datasets.line, {
spanGaps: true,
tension: 0.231
});
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [0, 0],
label: 'dataset1',
spanGaps: true,
backgroundColor: '#dad'
}],
labels: ['label1', 'label2']
},
options: {
datasets: {
line: {
tension: 0.345,
backgroundColor: '#add'
}
}
}
});
var options = chart.getDatasetMeta(0).dataset.options;
// dataset-level option overrides global default
expect(options.spanGaps).toBe(true);
// chart-level default overrides global default
expect(options.tension).toBe(0.345);
// dataset-level option overrides chart-level default
expect(options.backgroundColor).toBe('#dad');
});
});
it('should obey the chart-level dataset options', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [0, 0],
label: 'dataset1'
}],
labels: ['label1', 'label2']
},
options: {
datasets: {
line: {
spanGaps: true,
tension: 0.231,
backgroundColor: '#add',
borderWidth: '#daa',
borderColor: '#dad',
borderCapStyle: 'round',
borderDash: [0],
borderDashOffset: 0.871,
borderJoinStyle: 'miter',
fill: 'start',
cubicInterpolationMode: 'monotone'
}
}
}
});
var options = chart.getDatasetMeta(0).dataset.options;
expect(options.spanGaps).toBe(true);
expect(options.tension).toBe(0.231);
expect(options.backgroundColor).toBe('#add');
expect(options.borderWidth).toBe('#daa');
expect(options.borderColor).toBe('#dad');
expect(options.borderCapStyle).toBe('round');
expect(options.borderDash).toEqual([0]);
expect(options.borderDashOffset).toBe(0.871);
expect(options.borderJoinStyle).toBe('miter');
expect(options.fill).toBe('start');
expect(options.cubicInterpolationMode).toBe('monotone');
});
it('should obey the dataset options', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [0, 0],
label: 'dataset1',
spanGaps: true,
tension: 0.231,
backgroundColor: '#add',
borderWidth: '#daa',
borderColor: '#dad',
borderCapStyle: 'round',
borderDash: [0],
borderDashOffset: 0.871,
borderJoinStyle: 'miter',
fill: 'start',
cubicInterpolationMode: 'monotone'
}],
labels: ['label1', 'label2']
}
});
var options = chart.getDatasetMeta(0).dataset.options;
expect(options.spanGaps).toBe(true);
expect(options.tension).toBe(0.231);
expect(options.backgroundColor).toBe('#add');
expect(options.borderWidth).toBe('#daa');
expect(options.borderColor).toBe('#dad');
expect(options.borderCapStyle).toBe('round');
expect(options.borderDash).toEqual([0]);
expect(options.borderDashOffset).toBe(0.871);
expect(options.borderJoinStyle).toBe('miter');
expect(options.fill).toBe('start');
expect(options.cubicInterpolationMode).toBe('monotone');
});
it('should handle number of data point changes in update', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset1',
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
chart.data.datasets[0].data = [1, 2]; // remove 2 items
chart.update();
expect(meta.data.length).toBe(2);
expect(meta.data[0] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.PointElement).toBe(true);
chart.data.datasets[0].data = [1, 2, 3, 4, 5]; // add 3 items
chart.update();
expect(meta.data.length).toBe(5);
expect(meta.data[0] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[4] instanceof Chart.elements.PointElement).toBe(true);
});
describe('Interactions', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
labels: ['label1', 'label2', 'label3', 'label4'],
datasets: [{
data: [10, 15, 0, -4]
}]
},
options: {
scales: {
x: {
offset: true
}
},
elements: {
point: {
backgroundColor: 'rgb(100, 150, 200)',
borderColor: 'rgb(50, 100, 150)',
borderWidth: 2,
radius: 3
}
}
}
});
});
it ('should handle default hover styles', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('#3187DD');
expect(point.options.borderColor).toBe('#175A9D');
expect(point.options.borderWidth).toBe(1);
expect(point.options.radius).toBe(4);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(3);
});
it ('should handle hover styles defined via dataset properties', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.data.datasets[0], {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
hoverRadius: 4.2
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
expect(point.options.borderWidth).toBe(8.4);
expect(point.options.radius).toBe(4.2);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(3);
});
it('should handle hover styles defined via element options', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.options.elements.point, {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
hoverRadius: 4.2
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
expect(point.options.borderWidth).toBe(8.4);
expect(point.options.radius).toBe(4.2);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(3);
});
it('should handle dataset hover styles defined via dataset properties', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
var dataset = chart.getDatasetMeta(0).dataset;
Chart.helpers.merge(chart.data.datasets[0], {
backgroundColor: '#AAA',
borderColor: '#BBB',
borderWidth: 6,
hoverBackgroundColor: '#000',
hoverBorderColor: '#111',
hoverBorderWidth: 12
});
chart.options.hover = {mode: 'dataset'};
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(dataset.options.backgroundColor).toBe('#000');
expect(dataset.options.borderColor).toBe('#111');
expect(dataset.options.borderWidth).toBe(12);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(dataset.options.backgroundColor).toBe('#AAA');
expect(dataset.options.borderColor).toBe('#BBB');
expect(dataset.options.borderWidth).toBe(6);
});
});
it('should allow 0 as a point border width', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset1',
pointBorderWidth: 0
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
var point = meta.data[0];
expect(point.options.borderWidth).toBe(0);
});
it('should allow an array as the point border width setting', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset1',
pointBorderWidth: [1, 2, 3, 4]
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data[0].options.borderWidth).toBe(1);
expect(meta.data[1].options.borderWidth).toBe(2);
expect(meta.data[2].options.borderWidth).toBe(3);
expect(meta.data[3].options.borderWidth).toBe(4);
});
it('should render a million points', function() {
var data = [];
for (let x = 0; x < 1e6; x++) {
data.push({x, y: Math.sin(x / 10000)});
}
function createChart() {
window.acquireChart({
type: 'line',
data: {
datasets: [{
data,
borderWidth: 1,
radius: 0
}],
},
options: {
scales: {
x: {type: 'linear'},
y: {type: 'linear'}
}
}
});
}
expect(createChart).not.toThrow();
});
it('should set skipped points to the reset state', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, null, 0, -4],
label: 'dataset1',
pointBorderWidth: [1, 2, 3, 4]
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
var {x, y} = point.getProps(['x', 'y'], true);
expect(point.skip).toBe(true);
expect(isNaN(x)).toBe(false);
expect(isNaN(y)).toBe(false);
});
it('should honor spangap interval forwards', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
spanGaps: 10,
data: [{x: 10, y: 123}, {x: 15, y: 124}, {x: 26, y: 125}, {x: 30, y: 126}, {x: 35, y: 127}],
label: 'dataset1',
}],
},
options: {
scales: {
x: {
type: 'linear',
}
}
}
});
var meta = chart.getDatasetMeta(0);
for (var i = 0; i < meta.data.length; ++i) {
var point = meta.data[i];
expect(point.stop).toBe(i === 2);
}
});
it('should honor spangap interval backwards', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
spanGaps: 10,
data: [{x: 35, y: 123}, {x: 30, y: 124}, {x: 26, y: 125}, {x: 15, y: 126}, {x: 10, y: 127}],
label: 'dataset1',
}],
},
options: {
scales: {
x: {
type: 'linear',
}
}
}
});
var meta = chart.getDatasetMeta(0);
for (var i = 0; i < meta.data.length; ++i) {
var point = meta.data[i];
expect(point.stop).toBe(i === 3);
}
});
it('should correctly calc visible points on update', async() => {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [
{x: 10, y: 20},
{x: 15, y: 19},
]
}],
},
options: {
scales: {
y: {
type: 'linear',
min: 0,
max: 25,
},
x: {
type: 'linear',
min: 0,
max: 50
},
}
}
});
chart.data.datasets[0].data = [
{x: 10, y: 20},
{x: 15, y: 19},
{x: 17, y: 12},
{x: 50, y: 9},
{x: 50, y: 9},
{x: 50, y: 9},
{x: 51, y: 9},
{x: 52, y: 9},
{x: 52, y: 9},
];
chart.update();
var point = chart.getDatasetMeta(0).data[0];
var event = {
type: 'mousemove',
native: true,
...point
};
chart._handleEvent(event, false, true);
const visiblePoints = chart.getSortedVisibleDatasetMetas()[0].data.filter(_ => !_.skip);
expect(visiblePoints.length).toBe(6);
}, 500);
it('should correctly calc _drawStart and _drawCount when first points beyond scale limits are null and spanGaps=true', async() => {
var chart = window.acquireChart({
type: 'line',
data: {
labels: [0, 10, 20, 30, 40, 50],
datasets: [{
data: [3, null, 2, 3, null, 1.5],
spanGaps: true,
tension: 0.4
}]
},
options: {
scales: {
x: {
type: 'linear',
min: 11,
max: 40,
}
}
}
});
chart.update();
var controller = chart.getDatasetMeta(0).controller;
expect(controller._drawStart).toBe(0);
expect(controller._drawCount).toBe(6);
}, 500);
it('should correctly calc _drawStart and _drawCount when all points beyond scale limits are null and spanGaps=true', async() => {
var chart = window.acquireChart({
type: 'line',
data: {
labels: [0, 10, 20, 30, 40, 50],
datasets: [{
data: [null, null, 2, 3, null, null],
spanGaps: true,
tension: 0.4
}]
},
options: {
scales: {
x: {
type: 'linear',
min: 11,
max: 40,
}
}
}
});
chart.update();
var controller = chart.getDatasetMeta(0).controller;
expect(controller._drawStart).toBe(1);
expect(controller._drawCount).toBe(4);
}, 500);
it('should correctly calc _drawStart and _drawCount when spanGaps=false', async() => {
var chart = window.acquireChart({
type: 'line',
data: {
labels: [0, 10, 20, 30, 40, 50],
datasets: [{
data: [3, null, 2, 3, null, 1.5],
spanGaps: false,
tension: 0.4
}]
},
options: {
scales: {
x: {
type: 'linear',
min: 11,
max: 40,
}
}
}
});
chart.update();
var controller = chart.getDatasetMeta(0).controller;
expect(controller._drawStart).toBe(1);
expect(controller._drawCount).toBe(4);
}, 500);
it('should not override tooltip title and label callbacks', async() => {
const chart = window.acquireChart({
type: 'line',
data: {
labels: ['Label 1', 'Label 2'],
datasets: [{
data: [21, 79],
label: 'Dataset 1'
}, {
data: [33, 67],
label: 'Dataset 2'
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
}
});
const {tooltip} = chart;
const point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Label 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Dataset 1: 21'],
after: []
}]);
chart.options.plugins.tooltip = {mode: 'dataset'};
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Dataset 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Label 1: 21'],
after: []
}, {
before: [],
lines: ['Label 2: 79'],
after: []
}]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/scale.radialLinear.tests.js | test/specs/scale.radialLinear.tests.js | function getLabels(scale) {
return scale.ticks.map(t => t.label);
}
// Tests for the radial linear scale used by the polar area and radar charts
describe('Test the radial linear scale', function() {
describe('auto', jasmine.fixture.specs('scale.radialLinear'));
it('Should register the constructor with the registry', function() {
var Constructor = Chart.registry.getScale('radialLinear');
expect(Constructor).not.toBe(undefined);
expect(typeof Constructor).toBe('function');
});
it('Should have the correct default config', function() {
var defaultConfig = Chart.defaults.scales.radialLinear;
expect(defaultConfig).toEqual({
display: true,
animate: true,
position: 'chartArea',
angleLines: {
display: true,
color: 'rgba(0,0,0,0.1)',
lineWidth: 1,
borderDash: [],
borderDashOffset: 0.0
},
grid: {
circular: false
},
startAngle: 0,
ticks: {
color: Chart.defaults.color,
showLabelBackdrop: true,
callback: defaultConfig.ticks.callback
},
pointLabels: {
backdropColor: undefined,
backdropPadding: 2,
color: Chart.defaults.color,
display: true,
font: {
size: 10
},
callback: defaultConfig.pointLabels.callback,
padding: 5,
centerPointLabels: false
}
});
// Is this actually a function
expect(defaultConfig.ticks.callback).toEqual(jasmine.any(Function));
expect(defaultConfig.pointLabels.callback).toEqual(jasmine.any(Function));
});
it('Should correctly determine the max & min data values', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, -5, 78, -100]
}, {
data: [150]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5', 'label6']
},
options: {
scales: {}
}
});
expect(chart.scales.r.min).toBe(-100);
expect(chart.scales.r.max).toBe(150);
});
it('Should correctly determine the max & min of string data values', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: ['10', '5', '0', '-5', '78', '-100']
}, {
data: ['150']
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5', 'label6']
},
options: {
scales: {}
}
});
expect(chart.scales.r.min).toBe(-100);
expect(chart.scales.r.max).toBe(150);
});
it('Should correctly determine the max & min data values when there are hidden datasets', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: ['10', '5', '0', '-5', '78', '-100']
}, {
data: ['150']
}, {
data: [1000],
hidden: true
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5', 'label6']
},
options: {
scales: {}
}
});
expect(chart.scales.r.min).toBe(-100);
expect(chart.scales.r.max).toBe(150);
});
it('Should correctly determine the max & min data values when there is NaN data', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [50, 60, NaN, 70, null, undefined, Infinity, -Infinity]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5', 'label6', 'label7', 'label8']
},
options: {
scales: {}
}
});
expect(chart.scales.r.min).toBe(50);
expect(chart.scales.r.max).toBe(70);
});
it('Should ensure that the scale has a max and min that are not equal', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [],
labels: []
},
options: {
scales: {
rScale: {}
}
}
});
var scale = chart.scales.rScale;
expect(scale.min).toBe(-1);
expect(scale.max).toBe(1);
});
it('Should use the suggestedMin and suggestedMax options', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [1, 1, 1, 2, 1, 0]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5', 'label6']
},
options: {
scales: {
r: {
suggestedMin: -10,
suggestedMax: 10
}
}
}
});
expect(chart.scales.r.min).toBe(-10);
expect(chart.scales.r.max).toBe(10);
});
it('Should use the min and max options', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [1, 1, 1, 2, 1, 0]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5', 'label6']
},
options: {
scales: {
r: {
min: -1010,
max: 1010
}
}
}
});
expect(chart.scales.r.min).toBe(-1010);
expect(chart.scales.r.max).toBe(1010);
expect(getLabels(chart.scales.r)).toEqual(['-1,010', '-500', '0', '500', '1,010']);
});
it('should forcibly include 0 in the range if the beginAtZero option is used', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [20, 30, 40, 50]
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
scales: {
r: {
beginAtZero: false
}
}
}
});
expect(getLabels(chart.scales.r)).toEqual(['20', '25', '30', '35', '40', '45', '50']);
chart.scales.r.options.beginAtZero = true;
chart.update();
expect(getLabels(chart.scales.r)).toEqual(['0', '5', '10', '15', '20', '25', '30', '35', '40', '45', '50']);
chart.data.datasets[0].data = [-20, -30, -40, -50];
chart.update();
expect(getLabels(chart.scales.r)).toEqual(['-50', '-45', '-40', '-35', '-30', '-25', '-20', '-15', '-10', '-5', '0']);
chart.scales.r.options.beginAtZero = false;
chart.update();
expect(getLabels(chart.scales.r)).toEqual(['-50', '-45', '-40', '-35', '-30', '-25', '-20']);
});
it('Should generate tick marks in the correct order in reversed mode', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
reverse: true
}
}
}
});
expect(getLabels(chart.scales.r)).toEqual(['80', '70', '60', '50', '40', '30', '20', '10', '0']);
expect(chart.scales.r.start).toBe(80);
expect(chart.scales.r.end).toBe(0);
});
it('Should correctly limit the maximum number of ticks', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
labels: ['label1', 'label2', 'label3'],
datasets: [{
data: [0.5, 1.5, 2.5]
}]
},
options: {
scales: {
r: {
pointLabels: {
display: false
}
}
}
}
});
expect(getLabels(chart.scales.r)).toEqual(['0.5', '1.0', '1.5', '2.0', '2.5']);
chart.options.scales.r.ticks.maxTicksLimit = 11;
chart.update();
expect(getLabels(chart.scales.r)).toEqual(['0.5', '1.0', '1.5', '2.0', '2.5']);
chart.options.scales.r.ticks.stepSize = 0.01;
chart.update();
expect(getLabels(chart.scales.r)).toEqual(['0.5', '1.0', '1.5', '2.0', '2.5']);
chart.options.scales.r.min = 0.3;
chart.options.scales.r.max = 2.8;
chart.update();
expect(getLabels(chart.scales.r)).toEqual(['0.3', '0.8', '1.3', '1.8', '2.3', '2.8']);
});
it('Should build labels using the user supplied callback', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
ticks: {
callback: function(value, index) {
return index.toString();
}
}
}
}
}
});
expect(getLabels(chart.scales.r)).toEqual(['0', '1', '2', '3', '4', '5', '6', '7', '8']);
expect(chart.scales.r._pointLabels).toEqual(['label1', 'label2', 'label3', 'label4', 'label5']);
});
it('Should build point labels using the user supplied callback', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
pointLabels: {
callback: function(value, index) {
return index.toString();
}
}
}
}
}
});
expect(chart.scales.r._pointLabels).toEqual(['0', '1', '2', '3', '4']);
});
it('Should build point labels from falsy values', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78, 20]
}],
labels: [0, '', undefined, null, NaN, false]
}
});
expect(chart.scales.r._pointLabels).toEqual([0, '', '', '', '', '']);
});
it('Should build point labels considering hidden data', function() {
const chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [{
data: [10, 5, 0, 25, 78, 20]
}],
labels: ['a', 'b', 'c', 'd', 'e', 'f']
}
});
chart.toggleDataVisibility(3);
chart.update();
expect(chart.scales.r._pointLabels).toEqual(['a', 'b', 'c', 'e', 'f']);
});
it('should correctly set the center point', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
pointLabels: {
callback: function(value, index) {
return index.toString();
}
}
}
}
}
});
expect(chart.scales.r.drawingArea).toBe(215);
expect(chart.scales.r.xCenter).toBe(256);
expect(chart.scales.r.yCenter).toBe(280);
});
it('should correctly get the label for a given data index', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
pointLabels: {
callback: function(value, index) {
return index.toString();
}
}
}
}
}
});
expect(chart.scales.r.getLabelForValue(5)).toBe('5');
});
it('should get the correct distance from the center point', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
pointLabels: {
callback: function(value, index) {
return index.toString();
}
}
}
}
}
});
expect(chart.scales.r.getDistanceFromCenterForValue(chart.scales.r.min)).toBe(0);
expect(chart.scales.r.getDistanceFromCenterForValue(chart.scales.r.max)).toBe(215);
var position = chart.scales.r.getPointPositionForValue(1, 5);
expect(position.x).toBeCloseToPixel(269);
expect(position.y).toBeCloseToPixel(276);
chart.scales.r.options.reverse = true;
chart.update();
expect(chart.scales.r.getDistanceFromCenterForValue(chart.scales.r.min)).toBe(215);
expect(chart.scales.r.getDistanceFromCenterForValue(chart.scales.r.max)).toBe(0);
});
it('should get the correct value for a distance from the center point', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
pointLabels: {
callback: function(value, index) {
return index.toString();
}
}
}
}
}
});
expect(chart.scales.r.getValueForDistanceFromCenter(0)).toBe(chart.scales.r.min);
expect(chart.scales.r.getValueForDistanceFromCenter(215)).toBe(chart.scales.r.max);
var dist = chart.scales.r.getDistanceFromCenterForValue(5);
expect(chart.scales.r.getValueForDistanceFromCenter(dist)).toBe(5);
chart.scales.r.options.reverse = true;
chart.update();
expect(chart.scales.r.getValueForDistanceFromCenter(0)).toBe(chart.scales.r.max);
expect(chart.scales.r.getValueForDistanceFromCenter(215)).toBe(chart.scales.r.min);
});
it('should correctly get angles for all points', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
startAngle: 15,
pointLabels: {
callback: function(value, index) {
return index.toString();
}
}
}
},
}
});
var radToNearestDegree = function(rad) {
return Math.round((360 * rad) / (2 * Math.PI));
};
var slice = 72; // (360 / 5)
for (var i = 0; i < 5; i++) {
expect(radToNearestDegree(chart.scales.r.getIndexAngle(i))).toBe(15 + (slice * i));
}
chart.scales.r.options.startAngle = 0;
chart.update();
for (var x = 0; x < 5; x++) {
expect(radToNearestDegree(chart.scales.r.getIndexAngle(x))).toBe((slice * x));
}
});
it('should correctly get the correct label alignment for all points', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
pointLabels: {
callback: function(value, index) {
return index.toString();
}
},
ticks: {
display: false
}
}
}
}
});
var scale = chart.scales.r;
[{
startAngle: 30,
textAlign: ['right', 'right', 'left', 'left', 'left'],
}, {
startAngle: -30,
textAlign: ['right', 'right', 'left', 'left', 'right'],
}, {
startAngle: 750,
textAlign: ['right', 'right', 'left', 'left', 'left'],
}].forEach(function(expected) {
scale.options.startAngle = expected.startAngle;
chart.update();
scale.ctx = window.createMockContext();
chart.draw();
scale.ctx.getCalls().filter(function(x) {
return x.name === 'setTextAlign';
}).forEach(function(x, i) {
expect(x.args[0]).withContext('startAngle: ' + expected.startAngle + ', tick: ' + i).toBe(expected.textAlign[i]);
});
});
});
it('should correctly get the point positions in center', function() {
var chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}],
labels: ['label1', 'label2', 'label3', 'label4', 'label5']
},
options: {
scales: {
r: {
pointLabels: {
display: true,
padding: 5,
centerPointLabels: true
},
ticks: {
display: false
}
}
}
}
});
const PI = Math.PI;
const lavelNum = 5;
const padding = 5;
const pointLabelItems = chart.scales.r._pointLabelItems;
const additionalAngle = PI / lavelNum;
const opts = chart.scales.r.options;
const outerDistance = chart.scales.r.getDistanceFromCenterForValue(opts.ticks.reverse ? chart.scales.r.min : chart.scales.r.max);
const tickBackdropHeight = 0;
const yForAngle = function(y, h, angle) {
if (angle === 90 || angle === 270) {
y -= (h / 2);
} else if (angle > 270 || angle < 90) {
y -= h;
}
return y;
};
const toDegrees = function(radians) {
return radians * (180 / PI);
};
for (var i = 0; i < 5; i++) {
const extra = (i === 0 ? tickBackdropHeight / 2 : 0);
const pointLabelItem = pointLabelItems[i];
const pointPosition = chart.scales.r.getPointPosition(i, outerDistance + extra + padding, additionalAngle);
expect(pointLabelItem.x).toBe(pointPosition.x);
expect(pointLabelItem.y).toBe(yForAngle(pointPosition.y, 12, toDegrees(pointPosition.angle + PI / 2)));
}
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.animator.tests.js | test/specs/core.animator.tests.js | describe('Chart.animator', function() {
it('should fire onProgress for each draw', function(done) {
let count = 0;
let drawCount = 0;
const progress = (animation) => {
count++;
expect(animation.numSteps).toEqual(250);
expect(animation.currentStep <= 250).toBeTrue();
};
acquireChart({
type: 'bar',
data: {
datasets: [
{data: [10, 5, 0, 25, 78, -10]}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
animation: {
duration: 250,
onProgress: progress,
onComplete: function() {
expect(count).toEqual(drawCount);
done();
}
}
},
plugins: [{
afterDraw() {
drawCount++;
}
}]
}, {
canvas: {
height: 150,
width: 250
},
});
});
it('should not fail when adding no items', function() {
const chart = {};
Chart.animator.add(chart, undefined);
Chart.animator.add(chart, []);
Chart.animator.start(chart);
expect(Chart.animator.running(chart)).toBeFalse();
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/controller.bubble.tests.js | test/specs/controller.bubble.tests.js | describe('Chart.controllers.bubble', function() {
describe('auto', jasmine.fixture.specs('controller.bubble'));
it('should be registered as dataset controller', function() {
expect(typeof Chart.controllers.bubble).toBe('function');
});
it('should be constructed', function() {
var chart = window.acquireChart({
type: 'bubble',
data: {
datasets: [{
data: []
}]
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.type).toBe('bubble');
expect(meta.controller).not.toBe(undefined);
expect(meta.controller.index).toBe(0);
expect(meta.data).toEqual([]);
meta.controller.updateIndex(1);
expect(meta.controller.index).toBe(1);
});
it('should use the first scale IDs if the dataset does not specify them', function() {
var chart = window.acquireChart({
type: 'bubble',
data: {
datasets: [{
data: []
}]
},
});
var meta = chart.getDatasetMeta(0);
expect(meta.xAxisID).toBe('x');
expect(meta.yAxisID).toBe('y');
});
it('should create point elements for each data item during initialization', function() {
var chart = window.acquireChart({
type: 'bubble',
data: {
datasets: [{
data: [10, 15, 0, -4]
}]
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4); // 4 points created
expect(meta.data[0] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.PointElement).toBe(true);
});
it('should draw all elements', function() {
var chart = window.acquireChart({
type: 'bubble',
data: {
datasets: [{
data: [10, 15, 0, -4]
}]
},
options: {
animation: false,
showLine: true
}
});
var meta = chart.getDatasetMeta(0);
spyOn(meta.data[0], 'draw');
spyOn(meta.data[1], 'draw');
spyOn(meta.data[2], 'draw');
spyOn(meta.data[3], 'draw');
chart.update();
expect(meta.data[0].draw.calls.count()).toBe(1);
expect(meta.data[1].draw.calls.count()).toBe(1);
expect(meta.data[2].draw.calls.count()).toBe(1);
expect(meta.data[3].draw.calls.count()).toBe(1);
});
it('should update elements when modifying style', function() {
var chart = window.acquireChart({
type: 'bubble',
data: {
datasets: [{
data: [{
x: 10,
y: 10,
r: 5
}, {
x: -15,
y: -10,
r: 1
}, {
x: 0,
y: -9,
r: 2
}, {
x: -4,
y: 10,
r: 1
}]
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
plugins: {
legend: false,
title: false
},
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false
}
}
}
});
var meta = chart.getDatasetMeta(0);
[
{r: 5, x: 5, y: 5},
{r: 1, x: 171, y: 507},
{r: 2, x: 341, y: 482},
{r: 1, x: 507, y: 5}
].forEach(function(expected, i) {
expect(meta.data[i].x).toBeCloseToPixel(expected.x);
expect(meta.data[i].y).toBeCloseToPixel(expected.y);
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
backgroundColor: Chart.defaults.backgroundColor,
borderColor: Chart.defaults.borderColor,
borderWidth: 1,
hitRadius: 1,
radius: expected.r
}));
});
// Use dataset level styles for lines & points
chart.data.datasets[0].backgroundColor = 'rgb(98, 98, 98)';
chart.data.datasets[0].borderColor = 'rgb(8, 8, 8)';
chart.data.datasets[0].borderWidth = 0.55;
// point styles
chart.data.datasets[0].radius = 22;
chart.data.datasets[0].hitRadius = 3.3;
chart.update();
for (var i = 0; i < 4; ++i) {
expect(meta.data[i].options).toEqual(jasmine.objectContaining({
backgroundColor: 'rgb(98, 98, 98)',
borderColor: 'rgb(8, 8, 8)',
borderWidth: 0.55,
hitRadius: 3.3
}));
}
});
it('should handle number of data point changes in update', function() {
var chart = window.acquireChart({
type: 'bubble',
data: {
datasets: [{
data: [{
x: 10,
y: 10,
r: 5
}, {
x: -15,
y: -10,
r: 1
}, {
x: 0,
y: -9,
r: 2
}, {
x: -4,
y: 10,
r: 1
}]
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4);
chart.data.datasets[0].data = [{
x: 1,
y: 1,
r: 10
}, {
x: 10,
y: 5,
r: 2
}]; // remove 2 items
chart.update();
expect(meta.data.length).toBe(2);
expect(meta.data[0] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.PointElement).toBe(true);
chart.data.datasets[0].data = [{
x: 10,
y: 10,
r: 5
}, {
x: -15,
y: -10,
r: 1
}, {
x: 0,
y: -9,
r: 2
}, {
x: -4,
y: 10,
r: 1
}, {
x: -5,
y: 0,
r: 3
}]; // add 3 items
chart.update();
expect(meta.data.length).toBe(5);
expect(meta.data[0] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.PointElement).toBe(true);
expect(meta.data[4] instanceof Chart.elements.PointElement).toBe(true);
});
describe('Interactions', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'bubble',
data: {
labels: ['label1', 'label2', 'label3', 'label4'],
datasets: [{
data: [{
x: 5,
y: 5,
r: 20
}, {
x: -15,
y: -10,
r: 15
}, {
x: 15,
y: 10,
r: 10
}, {
x: -15,
y: 10,
r: 5
}]
}]
},
options: {
elements: {
point: {
backgroundColor: 'rgb(100, 150, 200)',
borderColor: 'rgb(50, 100, 150)',
borderWidth: 2,
radius: 3
}
}
}
});
});
it ('should handle default hover styles', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('#3187DD');
expect(point.options.borderColor).toBe('#175A9D');
expect(point.options.borderWidth).toBe(1);
expect(point.options.radius).toBe(20 + 4);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(20);
});
it ('should handle hover styles defined via dataset properties', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.data.datasets[0], {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
hoverRadius: 4.2
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
expect(point.options.borderWidth).toBe(8.4);
expect(point.options.radius).toBe(20 + 4.2);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(20);
});
it ('should handle hover styles defined via element options', async function() {
var chart = this.chart;
var point = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.options.elements.point, {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
hoverRadius: 4.2
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(point.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(point.options.borderColor).toBe('rgb(150, 50, 100)');
expect(point.options.borderWidth).toBe(8.4);
expect(point.options.radius).toBe(20 + 4.2);
await jasmine.triggerMouseEvent(chart, 'mouseout', point);
expect(point.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(point.options.borderColor).toBe('rgb(50, 100, 150)');
expect(point.options.borderWidth).toBe(2);
expect(point.options.radius).toBe(20);
});
});
it('should not override tooltip title and label callbacks', async() => {
const chart = window.acquireChart({
type: 'bubble',
data: {
labels: ['Label 1', 'Label 2'],
datasets: [{
data: [{
x: 10,
y: 15,
r: 15
},
{
x: 12,
y: 10,
r: 10
}],
label: 'Dataset 1'
}, {
data: [{
x: 20,
y: 10,
r: 5
},
{
x: 4,
y: 8,
r: 30
}],
label: 'Dataset 2'
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
}
});
const {tooltip} = chart;
const point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Label 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Dataset 1: (10, 15, 15)'],
after: []
}]);
chart.options.plugins.tooltip = {mode: 'dataset'};
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Dataset 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Label 1: (10, 15, 15)'],
after: []
}, {
before: [],
lines: ['Label 2: (12, 10, 10)'],
after: []
}]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/scale.time.tests.js | test/specs/scale.time.tests.js | // Time scale tests
describe('Time scale tests', function() {
describe('auto', jasmine.fixture.specs('scale.time'));
function createScale(data, options, dimensions) {
var width = (dimensions && dimensions.width) || 400;
var height = (dimensions && dimensions.height) || 50;
options = options || {};
options.type = 'time';
options.id = 'xScale0';
var chart = window.acquireChart({
type: 'line',
data: data,
options: {
scales: {
x: options
}
}
}, {canvas: {width: width, height: height}});
return chart.scales.x;
}
function getLabels(scale) {
return scale.ticks.map(t => t.label);
}
beforeEach(function() {
// Need a time matcher for getValueFromPixel
jasmine.addMatchers({
toBeCloseToTime: function() {
return {
compare: function(time, expected) {
var result = false;
var actual = moment(time);
var diff = actual.diff(expected.value, expected.unit, true);
result = Math.abs(diff) < (expected.threshold !== undefined ? expected.threshold : 0.01);
return {
pass: result
};
}
};
}
});
});
it('should load moment.js as a dependency', function() {
expect(window.moment).not.toBe(undefined);
});
it('should register the constructor with the registry', function() {
var Constructor = Chart.registry.getScale('time');
expect(Constructor).not.toBe(undefined);
expect(typeof Constructor).toBe('function');
});
it('should have the correct default config', function() {
var defaultConfig = Chart.defaults.scales.time;
expect(defaultConfig).toEqual({
bounds: 'data',
adapters: {},
time: {
parser: false, // false == a pattern string from or a custom callback that converts its argument to a timestamp
unit: false, // false == automatic or override with week, month, year, etc.
round: false, // none, or override with week, month, year, etc.
isoWeekday: false, // override week start day
minUnit: 'millisecond',
displayFormats: {}
},
ticks: {
source: 'auto',
callback: false,
major: {
enabled: false
}
}
});
});
it('should correctly determine the unit', function() {
var date = moment('Jan 01 1990', 'MMM DD YYYY');
var data = [];
for (var i = 0; i < 60; i++) {
data.push({x: date.valueOf(), y: Math.random()});
date = date.clone().add(1, 'month');
}
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
data: data
}],
},
options: {
scales: {
x: {
type: 'time',
ticks: {
source: 'data',
autoSkip: true
}
},
}
}
});
var scale = chart.scales.x;
expect(scale._unit).toEqual('month');
});
describe('when specifying limits', function() {
var mockData = {
labels: ['2015-01-01T20:00:00', '2015-01-02T20:00:00', '2015-01-03T20:00:00'],
};
var config;
beforeEach(function() {
config = Chart.helpers.clone(Chart.defaults.scales.time);
config.ticks.source = 'labels';
config.time.unit = 'day';
});
it('should use the min option when less than first label for building ticks', function() {
config.min = '2014-12-29T04:00:00';
var labels = getLabels(createScale(mockData, config));
expect(labels[0]).toEqual('Jan 1');
});
it('should use the min option when greater than first label for building ticks', function() {
config.min = '2015-01-02T04:00:00';
var labels = getLabels(createScale(mockData, config));
expect(labels[0]).toEqual('Jan 2');
});
it('should use the max option when greater than last label for building ticks', function() {
config.max = '2015-01-05T06:00:00';
var labels = getLabels(createScale(mockData, config));
expect(labels[labels.length - 1]).toEqual('Jan 3');
});
it('should use the max option when less than last label for building ticks', function() {
config.max = '2015-01-02T23:00:00';
var labels = getLabels(createScale(mockData, config));
expect(labels[labels.length - 1]).toEqual('Jan 2');
});
});
it('should use the isoWeekday option', function() {
var mockData = {
labels: [
'2015-01-01T20:00:00', // Thursday
'2015-01-02T20:00:00', // Friday
'2015-01-03T20:00:00' // Saturday
]
};
var config = Chart.helpers.mergeIf({
bounds: 'ticks',
time: {
unit: 'week',
isoWeekday: 3 // Wednesday
}
}, Chart.defaults.scales.time);
var scale = createScale(mockData, config);
var ticks = getLabels(scale);
expect(ticks).toEqual(['Dec 31, 2014', 'Jan 7, 2015']);
});
describe('when rendering several days', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
data: []
}],
labels: [
'2015-01-01T20:00:00',
'2015-01-02T21:00:00',
'2015-01-03T22:00:00',
'2015-01-05T23:00:00',
'2015-01-07T03:00',
'2015-01-08T10:00',
'2015-01-10T12:00'
]
},
options: {
scales: {
x: {
type: 'time',
position: 'bottom'
},
}
}
});
this.scale = this.chart.scales.x;
});
it('should be bounded by the nearest week beginnings', function() {
var chart = this.chart;
var scale = this.scale;
expect(scale.getValueForPixel(scale.left)).toBeGreaterThan(moment(chart.data.labels[0]).startOf('week'));
expect(scale.getValueForPixel(scale.right)).toBeLessThan(moment(chart.data.labels[chart.data.labels.length - 1]).add(1, 'week').endOf('week'));
});
it('should convert between screen coordinates and times', function() {
var chart = this.chart;
var scale = this.scale;
var timeRange = moment(scale.max).valueOf() - moment(scale.min).valueOf();
var msPerPix = timeRange / scale.width;
var firstPointOffsetMs = moment(chart.config.data.labels[0]).valueOf() - scale.min;
var firstPointPixel = scale.left + firstPointOffsetMs / msPerPix;
var lastPointOffsetMs = moment(chart.config.data.labels[chart.config.data.labels.length - 1]).valueOf() - scale.min;
var lastPointPixel = scale.left + lastPointOffsetMs / msPerPix;
expect(scale.getPixelForValue(moment('2015-01-01T20:00:00').valueOf())).toBeCloseToPixel(firstPointPixel);
expect(scale.getPixelForValue(moment(chart.data.labels[0]).valueOf())).toBeCloseToPixel(firstPointPixel);
expect(scale.getValueForPixel(firstPointPixel)).toBeCloseToTime({
value: moment(chart.data.labels[0]),
unit: 'hour',
});
expect(scale.getPixelForValue(moment('2015-01-10T12:00').valueOf())).toBeCloseToPixel(lastPointPixel);
expect(scale.getValueForPixel(lastPointPixel)).toBeCloseToTime({
value: moment(chart.data.labels[6]),
unit: 'hour'
});
});
});
describe('when rendering several years', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
labels: ['2005-07-04', '2017-01-20'],
},
options: {
scales: {
x: {
type: 'time',
bounds: 'ticks',
position: 'bottom'
},
}
}
}, {canvas: {width: 800, height: 200}});
this.scale = this.chart.scales.x;
});
it('should be bounded by nearest step\'s year start and end', function() {
var scale = this.scale;
var ticks = scale.getTicks();
var step = ticks[1].value - ticks[0].value;
var stepsAmount = Math.floor((scale.max - scale.min) / step);
expect(scale.getValueForPixel(scale.left)).toBeCloseToTime({
value: moment(scale.min).startOf('year'),
unit: 'hour',
});
expect(scale.getValueForPixel(scale.right)).toBeCloseToTime({
value: moment(scale.min + step * stepsAmount).endOf('year'),
unit: 'hour',
});
});
it('should build the correct ticks', function() {
expect(getLabels(this.scale)).toEqual(['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018']);
});
it('should have ticks with accurate labels', function() {
var scale = this.scale;
var ticks = scale.getTicks();
// pixelsPerTick is an approximation which assumes same number of milliseconds per year (not true)
// we use a threshold of 1 day so that we still match these values
var pixelsPerTick = scale.width / (ticks.length - 1);
for (var i = 0; i < ticks.length - 1; i++) {
var offset = pixelsPerTick * i;
expect(scale.getValueForPixel(scale.left + offset)).toBeCloseToTime({
value: moment(ticks[i].label + '-01-01'),
unit: 'day',
threshold: 1,
});
}
});
});
it('should get the correct label for a data value', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
data: [null, 10, 3]
}],
labels: ['2015-01-01T20:00:00', '2015-01-02T21:00:00', '2015-01-03T22:00:00', '2015-01-05T23:00:00', '2015-01-07T03:00', '2015-01-08T10:00', '2015-01-10T12:00'], // days
},
options: {
scales: {
x: {
type: 'time',
position: 'bottom',
ticks: {
source: 'labels',
autoSkip: false
}
}
}
}
});
var xScale = chart.scales.x;
var controller = chart.getDatasetMeta(0).controller;
expect(xScale.getLabelForValue(controller.getParsed(0)[xScale.id])).toBeTruthy();
expect(xScale.getLabelForValue(controller.getParsed(0)[xScale.id])).toBe('Jan 1, 2015, 8:00:00 pm');
expect(xScale.getLabelForValue(xScale.getValueForPixel(xScale.getPixelForTick(6)))).toBe('Jan 10, 2015, 12:00:00 pm');
});
describe('when ticks.callback is specified', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
data: [0, 0]
}],
labels: ['2015-01-01T20:00:00', '2015-01-01T20:01:00']
},
options: {
scales: {
x: {
type: 'time',
time: {
displayFormats: {
second: 'h:mm:ss'
}
},
ticks: {
callback: function(_, i) {
return '<' + i + '>';
}
}
}
}
}
});
this.scale = this.chart.scales.x;
});
it('should get the correct labels for ticks', function() {
var labels = getLabels(this.scale);
expect(labels.length).toEqual(21);
expect(labels[0]).toEqual('<0>');
expect(labels[labels.length - 1]).toEqual('<60>');
});
it('should update ticks.callback correctly', function() {
var chart = this.chart;
chart.options.scales.x.ticks.callback = function(_, i) {
return '{' + i + '}';
};
chart.update();
var labels = getLabels(this.scale);
expect(labels.length).toEqual(21);
expect(labels[0]).toEqual('{0}');
expect(labels[labels.length - 1]).toEqual('{60}');
});
});
it('should get the correct label when time is specified as a string', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
data: [{x: '2015-01-01T20:00:00', y: 10}, {x: '2015-01-02T21:00:00', y: 3}]
}],
},
options: {
scales: {
x: {
type: 'time',
position: 'bottom'
},
}
}
});
var xScale = chart.scales.x;
var controller = chart.getDatasetMeta(0).controller;
var value = controller.getParsed(0)[xScale.id];
expect(xScale.getLabelForValue(value)).toBeTruthy();
expect(xScale.getLabelForValue(value)).toBe('Jan 1, 2015, 8:00:00 pm');
});
it('should get the correct label for a data value by format', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
data: [null, 10, 3]
}],
labels: ['2015-01-01T20:00:00', '2015-01-02T21:00:00', '2015-01-03T22:00:00', '2015-01-05T23:00:00', '2015-01-07T03:00', '2015-01-08T10:00', '2015-01-10T12:00'], // days
},
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'day',
displayFormats: {
day: 'YYYY-MM-DD'
}
},
position: 'bottom',
ticks: {
source: 'labels',
autoSkip: false
}
}
}
}
});
var xScale = chart.scales.x;
for (const lbl of chart.data.labels) {
var dd = xScale._adapter.parse(lbl);
var parsed = lbl.split('T');
expect(xScale.format(dd)).toBe(parsed[0]);
}
for (const lbl of chart.data.labels) {
var mm = xScale._adapter.parse(lbl);
var yearMonth = lbl.substring(0, 7);
expect(xScale.format(mm, 'YYYY-MM')).toBe(yearMonth);
}
});
it('should round to isoWeekday', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [{x: '2020-04-12T20:00:00', y: 1}, {x: '2020-04-13T20:00:00', y: 2}]
}]
},
options: {
scales: {
x: {
type: 'time',
ticks: {
source: 'data'
},
time: {
unit: 'week',
round: 'week',
isoWeekday: 1,
displayFormats: {
week: 'WW'
}
}
},
}
}
});
expect(getLabels(chart.scales.x)).toEqual(['15', '16']);
});
it('should get the correct label for a timestamp', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
data: [
// Normally (at least with the moment.js adapter), times would be in
// the user's local time zone. To allow for more stable tests, our
// tests/index.js sets moment.js to use UTC; use `Z` here to match.
{t: +new Date('2018-01-08 05:14:23.234Z'), y: 10},
{t: +new Date('2018-01-09 06:17:43.426Z'), y: 3}
]
}],
},
options: {
parsing: {xAxisKey: 't'},
scales: {
x: {
type: 'time',
position: 'bottom'
},
}
}
});
var xScale = chart.scales.x;
var controller = chart.getDatasetMeta(0).controller;
var label = xScale.getLabelForValue(controller.getParsed(0)[xScale.id]);
expect(label).toEqual('Jan 8, 2018, 5:14:23 am');
});
it('should get the correct pixel for only one data in the dataset', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: ['2016-05-27'],
datasets: [{
xAxisID: 'x',
data: [5]
}]
},
options: {
scales: {
x: {
display: true,
type: 'time'
}
}
}
});
var xScale = chart.scales.x;
var pixel = xScale.getPixelForValue(moment('2016-05-27').valueOf());
expect(xScale.getValueForPixel(pixel)).toEqual(moment(chart.data.labels[0]).valueOf());
});
it('does not create a negative width chart when hidden', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: []
}]
},
options: {
scales: {
x: {
type: 'time',
ticks: {
min: moment().subtract(1, 'months'),
max: moment(),
}
},
},
responsive: true,
},
}, {
wrapper: {
style: 'display: none',
},
});
expect(chart.scales.y.width).toEqual(0);
expect(chart.scales.y.maxWidth).toEqual(0);
expect(chart.width).toEqual(0);
});
describe('when ticks.source', function() {
describe('is "labels"', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
labels: ['2017', '2019', '2020', '2025', '2042'],
datasets: [{data: [0, 1, 2, 3, 4, 5]}]
},
options: {
scales: {
x: {
type: 'time',
time: {
parser: 'YYYY'
},
ticks: {
source: 'labels'
}
}
}
}
});
});
it ('should generate ticks from "data.labels"', function() {
var scale = this.chart.scales.x;
expect(scale.min).toEqual(+moment('2017', 'YYYY'));
expect(scale.max).toEqual(+moment('2042', 'YYYY'));
expect(getLabels(scale)).toEqual([
'2017', '2019', '2020', '2025', '2042']);
});
it ('should not add ticks for min and max if they extend the labels range', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.min = '2012';
options.max = '2051';
chart.update();
expect(scale.min).toEqual(+moment('2012', 'YYYY'));
expect(scale.max).toEqual(+moment('2051', 'YYYY'));
expect(getLabels(scale)).toEqual([
'2017', '2019', '2020', '2025', '2042']);
});
it ('should not duplicate ticks if min and max are the labels limits', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.min = '2017';
options.max = '2042';
chart.update();
expect(scale.min).toEqual(+moment('2017', 'YYYY'));
expect(scale.max).toEqual(+moment('2042', 'YYYY'));
expect(getLabels(scale)).toEqual([
'2017', '2019', '2020', '2025', '2042']);
});
it ('should correctly handle empty `data.labels` using "day" if `time.unit` is undefined`', function() {
var chart = this.chart;
var scale = chart.scales.x;
chart.data.labels = [];
chart.update();
expect(scale.min).toEqual(+moment().startOf('day'));
expect(scale.max).toEqual(+moment().endOf('day') + 1);
expect(getLabels(scale)).toEqual([]);
});
it ('should correctly handle empty `data.labels` using `time.unit`', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.time.unit = 'year';
chart.data.labels = [];
chart.update();
expect(scale.min).toEqual(+moment().startOf('year'));
expect(scale.max).toEqual(+moment().endOf('year') + 1);
expect(getLabels(scale)).toEqual([]);
});
});
describe('is "data"', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
labels: ['2017', '2019', '2020', '2025', '2042'],
datasets: [
{data: [0, 1, 2, 3, 4, 5]},
{data: [
{x: '2018', y: 6},
{x: '2020', y: 7},
{x: '2043', y: 8}
]}
]
},
options: {
scales: {
x: {
type: 'time',
time: {
parser: 'YYYY'
},
ticks: {
source: 'data'
}
}
}
}
});
});
it ('should generate ticks from "datasets.data"', function() {
var scale = this.chart.scales.x;
expect(scale.min).toEqual(+moment('2017', 'YYYY'));
expect(scale.max).toEqual(+moment('2043', 'YYYY'));
expect(getLabels(scale)).toEqual([
'2017', '2018', '2019', '2020', '2025', '2042', '2043']);
});
it ('should not add ticks for min and max if they extend the labels range', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.min = '2012';
options.max = '2051';
chart.update();
expect(scale.min).toEqual(+moment('2012', 'YYYY'));
expect(scale.max).toEqual(+moment('2051', 'YYYY'));
expect(getLabels(scale)).toEqual([
'2017', '2018', '2019', '2020', '2025', '2042', '2043']);
});
it ('should not duplicate ticks if min and max are the labels limits', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.min = '2017';
options.max = '2043';
chart.update();
expect(scale.min).toEqual(+moment('2017', 'YYYY'));
expect(scale.max).toEqual(+moment('2043', 'YYYY'));
expect(getLabels(scale)).toEqual([
'2017', '2018', '2019', '2020', '2025', '2042', '2043']);
});
it ('should correctly handle empty `data.labels` using "day" if `time.unit` is undefined`', function() {
var chart = this.chart;
var scale = chart.scales.x;
chart.data.labels = [];
chart.update();
expect(scale.min).toEqual(+moment('2018', 'YYYY'));
expect(scale.max).toEqual(+moment('2043', 'YYYY'));
expect(getLabels(scale)).toEqual([
'2018', '2020', '2043']);
});
it ('should correctly handle empty `data.labels` and hidden datasets using `time.unit`', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.time.unit = 'year';
chart.data.labels = [];
var meta = chart.getDatasetMeta(1);
meta.hidden = true;
chart.update();
expect(scale.min).toEqual(+moment().startOf('year'));
expect(scale.max).toEqual(+moment().endOf('year') + 1);
expect(getLabels(scale)).toEqual([]);
});
});
});
[true, false].forEach(function(normalized) {
describe('when normalized is ' + normalized + ' and scale type', function() {
describe('is "timeseries"', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
labels: ['2017', '2019', '2020', '2025', '2042'],
datasets: [{data: [0, 1, 2, 3, 4]}]
},
options: {
normalized,
scales: {
x: {
type: 'timeseries',
time: {
parser: 'YYYY'
},
ticks: {
source: 'labels'
}
},
y: {
display: false
}
}
}
});
});
it ('should space data out with the same gap, whatever their time values', function() {
var scale = this.chart.scales.x;
var start = scale.left;
var slice = scale.width / 4;
expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice);
expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * 2);
expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * 3);
expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * 4);
});
it ('should add a step before if scale.min is before the first data', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.min = '2012';
chart.update();
var start = scale.left;
var slice = scale.width / 5;
expect(scale.getPixelForValue(moment('2017').valueOf(), 1)).toBeCloseToPixel(86);
expect(scale.getPixelForValue(moment('2042').valueOf(), 5)).toBeCloseToPixel(start + slice * 5);
});
it ('should add a step after if scale.max is after the last data', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.max = '2050';
chart.update();
var start = scale.left;
expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(388);
});
it ('should add steps before and after if scale.min/max are outside the data range', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.min = '2012';
options.max = '2050';
chart.update();
expect(scale.getPixelForValue(moment('2017').valueOf(), 1)).toBeCloseToPixel(71);
expect(scale.getPixelForValue(moment('2042').valueOf(), 5)).toBeCloseToPixel(401);
});
});
describe('is "time"', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
labels: ['2017', '2019', '2020', '2025', '2042'],
datasets: [{data: [0, 1, 2, 3, 4, 5]}]
},
options: {
scales: {
x: {
type: 'time',
time: {
parser: 'YYYY'
},
ticks: {
source: 'labels'
}
},
y: {
display: false
}
}
}
});
});
it ('should space data out with a gap relative to their time values', function() {
var scale = this.chart.scales.x;
var start = scale.left;
var slice = scale.width / (2042 - 2017);
expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start);
expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice * (2019 - 2017));
expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * (2020 - 2017));
expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * (2025 - 2017));
expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * (2042 - 2017));
});
it ('should take in account scale min and max if outside the ticks range', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
options.min = '2012';
options.max = '2050';
chart.update();
var start = scale.left;
var slice = scale.width / (2050 - 2012);
expect(scale.getPixelForValue(moment('2017').valueOf(), 0)).toBeCloseToPixel(start + slice * (2017 - 2012));
expect(scale.getPixelForValue(moment('2019').valueOf(), 1)).toBeCloseToPixel(start + slice * (2019 - 2012));
expect(scale.getPixelForValue(moment('2020').valueOf(), 2)).toBeCloseToPixel(start + slice * (2020 - 2012));
expect(scale.getPixelForValue(moment('2025').valueOf(), 3)).toBeCloseToPixel(start + slice * (2025 - 2012));
expect(scale.getPixelForValue(moment('2042').valueOf(), 4)).toBeCloseToPixel(start + slice * (2042 - 2012));
});
});
});
});
describe('when bounds', function() {
describe('is "data"', function() {
it ('should preserve the data range', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: ['02/20 08:00', '02/21 09:00', '02/22 10:00', '02/23 11:00'],
datasets: [{data: [0, 1, 2, 3, 4, 5]}]
},
options: {
scales: {
x: {
type: 'time',
bounds: 'data',
time: {
parser: 'MM/DD HH:mm',
unit: 'day'
}
},
y: {
display: false
}
}
}
});
var scale = chart.scales.x;
expect(scale.min).toEqual(+moment('02/20 08:00', 'MM/DD HH:mm'));
expect(scale.max).toEqual(+moment('02/23 11:00', 'MM/DD HH:mm'));
expect(scale.getPixelForValue(moment('02/20 08:00', 'MM/DD HH:mm').valueOf())).toBeCloseToPixel(scale.left);
expect(scale.getPixelForValue(moment('02/23 11:00', 'MM/DD HH:mm').valueOf())).toBeCloseToPixel(scale.left + scale.width);
expect(getLabels(scale)).toEqual([
'Feb 21', 'Feb 22', 'Feb 23']);
});
});
describe('is "labels"', function() {
it('should preserve the label range', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: ['02/20 08:00', '02/21 09:00', '02/22 10:00', '02/23 11:00'],
datasets: [{data: [0, 1, 2, 3, 4, 5]}]
},
options: {
scales: {
x: {
type: 'time',
bounds: 'ticks',
time: {
parser: 'MM/DD HH:mm',
unit: 'day'
}
},
y: {
display: false
}
}
}
});
var scale = chart.scales.x;
var ticks = scale.getTicks();
expect(scale.min).toEqual(ticks[0].value);
expect(scale.max).toEqual(ticks[ticks.length - 1].value);
expect(scale.getPixelForValue(moment('02/20 08:00', 'MM/DD HH:mm').valueOf())).toBeCloseToPixel(60);
expect(scale.getPixelForValue(moment('02/23 11:00', 'MM/DD HH:mm').valueOf())).toBeCloseToPixel(426);
expect(getLabels(scale)).toEqual([
'Feb 20', 'Feb 21', 'Feb 22', 'Feb 23', 'Feb 24']);
});
});
});
describe('when min and/or max are defined', function() {
['auto', 'data', 'labels'].forEach(function(source) {
['data', 'ticks'].forEach(function(bounds) {
describe('and ticks.source is "' + source + '" and bounds "' + bounds + '"', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
labels: ['02/20 08:00', '02/21 09:00', '02/22 10:00', '02/23 11:00'],
datasets: [{data: [0, 1, 2, 3, 4, 5]}]
},
options: {
scales: {
x: {
type: 'time',
bounds: bounds,
time: {
parser: 'MM/DD HH:mm',
unit: 'day'
},
ticks: {
source: source
}
},
y: {
display: false
}
}
}
});
});
it ('should expand scale to the min/max range', function() {
var chart = this.chart;
var scale = chart.scales.x;
var options = chart.options.scales.x;
var min = '02/19 07:00';
var max = '02/24 08:00';
var minMillis = +moment(min, 'MM/DD HH:mm');
var maxMillis = +moment(max, 'MM/DD HH:mm');
options.min = min;
options.max = max;
chart.update();
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | true |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.segment.tests.js | test/specs/helpers.segment.tests.js | const {_boundSegment} = Chart.helpers;
describe('helpers.segments', function() {
describe('_boundSegment', function() {
const points = [{x: 10, y: 1}, {x: 20, y: 2}, {x: 30, y: 3}];
const segment = {start: 0, end: 2, loop: false};
it('should not find segment from before the line', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 5, end: 9.99999})).toEqual([]);
});
it('should not find segment from after the line', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 30.00001, end: 800})).toEqual([]);
});
it('should find segment when starting before line', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 5, end: 15})).toEqual([{start: 0, end: 1, loop: false, style: undefined}]);
});
it('should find segment directly on point', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 10, end: 10})).toEqual([{start: 0, end: 0, loop: false, style: undefined}]);
});
it('should find segment from range between points', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 11, end: 14})).toEqual([{start: 0, end: 1, loop: false, style: undefined}]);
});
it('should find segment from point between points', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 22, end: 22})).toEqual([{start: 1, end: 2, loop: false, style: undefined}]);
});
it('should find whole segment', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 0, end: 50})).toEqual([{start: 0, end: 2, loop: false, style: undefined}]);
});
it('should find correct segment from near points', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 10.001, end: 29.999})).toEqual([{start: 0, end: 2, loop: false, style: undefined}]);
});
it('should find segment from after the line', function() {
expect(_boundSegment(segment, points, {property: 'x', start: 25, end: 35})).toEqual([{start: 1, end: 2, loop: false, style: undefined}]);
});
it('should find multiple segments', function() {
const points2 = [{x: 0, y: 100}, {x: 1, y: 50}, {x: 2, y: 70}, {x: 4, y: 80}, {x: 5, y: -100}];
expect(_boundSegment({start: 0, end: 4, loop: false}, points2, {property: 'y', start: 60, end: 60})).toEqual([
{start: 0, end: 1, loop: false, style: undefined},
{start: 1, end: 2, loop: false, style: undefined},
{start: 3, end: 4, loop: false, style: undefined},
]);
});
it('should find correct segments when there are multiple points with same property value', function() {
const repeatedPoints = [{x: 1, y: 5}, {x: 1, y: 6}, {x: 2, y: 5}, {x: 2, y: 6}, {x: 3, y: 5}, {x: 3, y: 6}, {x: 3, y: 7}];
expect(_boundSegment({start: 0, end: 6, loop: false}, repeatedPoints, {property: 'x', start: 1, end: 1.1})).toEqual([{start: 0, end: 2, loop: false, style: undefined}]);
expect(_boundSegment({start: 0, end: 6, loop: false}, repeatedPoints, {property: 'x', start: 2, end: 2.1})).toEqual([{start: 2, end: 4, loop: false, style: undefined}]);
expect(_boundSegment({start: 0, end: 6, loop: false}, repeatedPoints, {property: 'x', start: 2, end: 3.1})).toEqual([{start: 2, end: 6, loop: false, style: undefined}]);
expect(_boundSegment({start: 0, end: 6, loop: false}, repeatedPoints, {property: 'x', start: 0, end: 8})).toEqual([{start: 0, end: 6, loop: false, style: undefined}]);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/element.bar.tests.js | test/specs/element.bar.tests.js | // Test the bar element
describe('Bar element tests', function() {
it('Should correctly identify as in range', function() {
var bar = new Chart.elements.BarElement({
base: 0,
width: 4,
x: 10,
y: 15
});
expect(bar.inRange(10, 15)).toBe(true);
expect(bar.inRange(10, 10)).toBe(true);
expect(bar.inRange(10, 16)).toBe(false);
expect(bar.inRange(5, 5)).toBe(false);
// Test when the y is below the base (negative bar)
var negativeBar = new Chart.elements.BarElement({
base: 0,
width: 4,
x: 10,
y: -15
});
expect(negativeBar.inRange(10, -16)).toBe(false);
expect(negativeBar.inRange(10, 1)).toBe(false);
expect(negativeBar.inRange(10, -5)).toBe(true);
});
it('should get the correct tooltip position', function() {
var bar = new Chart.elements.BarElement({
base: 0,
width: 4,
x: 10,
y: 15
});
expect(bar.tooltipPosition()).toEqual({
x: 10,
y: 15,
});
// Test when the y is below the base (negative bar)
var negativeBar = new Chart.elements.BarElement({
base: -10,
width: 4,
x: 10,
y: -15
});
expect(negativeBar.tooltipPosition()).toEqual({
x: 10,
y: -15,
});
});
it('should get the center', function() {
var bar = new Chart.elements.BarElement({
base: 0,
width: 4,
x: 10,
y: 15
});
expect(bar.getCenterPoint()).toEqual({x: 10, y: 7.5});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/plugin.filler.tests.js | test/specs/plugin.filler.tests.js | describe('Plugin.filler', function() {
const fillerPluginRegisterWarning = 'Tried to use the \'fill\' option without the \'Filler\' plugin enabled. Please import and register the \'Filler\' plugin and make sure it is not disabled in the options';
function decodedFillValues(chart) {
return chart.data.datasets.map(function(dataset, index) {
var meta = chart.getDatasetMeta(index) || {};
expect(meta.$filler).toBeDefined();
return meta.$filler.fill;
});
}
describe('auto', jasmine.fixture.specs('plugin.filler'));
describe('dataset.fill', function() {
it('Should show a warning when trying to use the filler plugin in the dataset when it\'s not registered', function() {
spyOn(console, 'warn');
Chart.unregister(Chart.Filler);
window.acquireChart({
type: 'line',
data: {
datasets: [{
fill: true
}]
}
});
expect(console.warn).toHaveBeenCalledWith(fillerPluginRegisterWarning);
Chart.register(Chart.Filler);
});
it('Should show a warning when trying to use the filler plugin in the root options when it\'s not registered', function() {
// jasmine.createSpy('warn');
spyOn(console, 'warn');
Chart.unregister(Chart.Filler);
window.acquireChart({
type: 'line',
data: {
datasets: [{
}]
},
options: {
fill: true
}
});
expect(console.warn).toHaveBeenCalledWith(fillerPluginRegisterWarning);
Chart.register(Chart.Filler);
});
it('should support boundaries', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: 'origin'},
{fill: 'start'},
{fill: 'end'},
]
}
});
expect(decodedFillValues(chart)).toEqual(['origin', 'start', 'end']);
});
it('should support absolute dataset index', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: 1},
{fill: 3},
{fill: 0},
{fill: 2},
]
}
});
expect(decodedFillValues(chart)).toEqual([1, 3, 0, 2]);
});
it('should support relative dataset index', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: '+3'},
{fill: '-1'},
{fill: '+1'},
{fill: '-2'},
]
}
});
expect(decodedFillValues(chart)).toEqual([
3, // 0 + 3
0, // 1 - 1
3, // 2 + 1
1, // 3 - 2
]);
});
it('should handle default fill when true (origin)', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: true},
{fill: false},
]
}
});
expect(decodedFillValues(chart)).toEqual(['origin', false]);
});
it('should ignore self dataset index', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: 0},
{fill: '-0'},
{fill: '+0'},
{fill: 3},
]
}
});
expect(decodedFillValues(chart)).toEqual([
false, // 0 === 0
false, // 1 === 1 - 0
false, // 2 === 2 + 0
false, // 3 === 3
]);
});
it('should ignore out of bounds dataset index', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: -2},
{fill: 4},
{fill: '-3'},
{fill: '+1'},
]
}
});
expect(decodedFillValues(chart)).toEqual([
false, // 0 - 2 < 0
false, // 1 + 4 > 3
false, // 2 - 3 < 0
false, // 3 + 1 > 3
]);
});
it('should ignore invalid values', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: 'foo'},
{fill: '+foo'},
{fill: '-foo'},
{fill: '+1.1'},
{fill: '-2.2'},
{fill: 3.3},
{fill: -4.4},
{fill: NaN},
{fill: Infinity},
{fill: ''},
{fill: null},
{fill: []},
]
}
});
expect(decodedFillValues(chart)).toEqual([
false, // NaN (string)
false, // NaN (string)
false, // NaN (string)
false, // float (string)
false, // float (string)
false, // float (number)
false, // float (number)
false, // NaN
false, // !isFinite
false, // empty string
false, // null
false, // array
]);
});
});
describe('options.plugins.filler.propagate', function() {
it('should compute propagated fill targets if true', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: 'start', hidden: true},
{fill: '-1', hidden: true},
{fill: 1, hidden: true},
{fill: '-2', hidden: true},
{fill: '+1'},
{fill: '+2'},
{fill: '-1'},
{fill: 'end', hidden: true},
]
},
options: {
plugins: {
filler: {
propagate: true
}
}
}
});
expect(decodedFillValues(chart)).toEqual([
'start', // 'start'
'start', // 1 - 1 -> 0 (hidden) -> 'start'
'start', // 1 (hidden) -> 0 (hidden) -> 'start'
'start', // 3 - 2 -> 1 (hidden) -> 0 (hidden) -> 'start'
5, // 4 + 1
'end', // 5 + 2 -> 7 (hidden) -> 'end'
5, // 6 - 1 -> 5
'end', // 'end'
]);
});
it('should preserve initial fill targets if false', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: 'start', hidden: true},
{fill: '-1', hidden: true},
{fill: 1, hidden: true},
{fill: '-2', hidden: true},
{fill: '+1'},
{fill: '+2'},
{fill: '-1'},
{fill: 'end', hidden: true},
]
},
options: {
plugins: {
filler: {
propagate: false
}
}
}
});
expect(decodedFillValues(chart)).toEqual([
'start', // 'origin'
0, // 1 - 1
1, // 1
1, // 3 - 2
5, // 4 + 1
7, // 5 + 2
5, // 6 - 1
'end', // 'end'
]);
});
it('should prevent recursive propagation', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [
{fill: '+2', hidden: true},
{fill: '-1', hidden: true},
{fill: '-1', hidden: true},
{fill: '-2'}
]
},
options: {
plugins: {
filler: {
propagate: true
}
}
}
});
expect(decodedFillValues(chart)).toEqual([
false, // 0 + 2 -> 2 (hidden) -> 1 (hidden) -> 0 (loop)
false, // 1 - 1 -> 0 (hidden) -> 2 (hidden) -> 1 (loop)
false, // 2 - 1 -> 1 (hidden) -> 0 (hidden) -> 2 (loop)
false, // 3 - 2 -> 1 (hidden) -> 0 (hidden) -> 2 (hidden) -> 1 (loop)
]);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.animation.tests.js | test/specs/core.animation.tests.js | describe('Chart.Animation', function() {
it('should animate boolean', function() {
const target = {prop: false};
const anim = new Chart.Animation({duration: 1000}, target, 'prop', true);
expect(anim.active()).toBeTrue();
anim.tick(anim._start + 500);
expect(anim.active()).toBeTrue();
expect(target.prop).toBeFalse();
anim.tick(anim._start + 501);
expect(anim.active()).toBeTrue();
expect(target.prop).toBeTrue();
anim.tick(anim._start - 100);
expect(anim.active()).toBeTrue();
expect(target.prop).toBeFalse();
anim.tick(anim._start + 1000);
expect(anim.active()).toBeFalse();
expect(target.prop).toBeTrue();
});
describe('color', function() {
it('should fall back to transparent', function() {
const target = {};
const anim = new Chart.Animation({duration: 1000, type: 'color'}, target, 'color', 'red');
anim._from = undefined;
anim.tick(anim._start + 500);
expect(target.color).toEqual('#FF000080');
anim._from = 'blue';
anim._to = undefined;
anim.tick(anim._start + 500);
expect(target.color).toEqual('#0000FF80');
});
it('should not try to mix invalid color', function() {
const target = {color: 'blue'};
const anim = new Chart.Animation({duration: 1000, type: 'color'}, target, 'color', 'invalid');
anim.tick(anim._start + 500);
expect(target.color).toEqual('invalid');
});
});
it('should loop', function() {
const target = {value: 0};
const anim = new Chart.Animation({duration: 100, loop: true}, target, 'value', 10);
anim.tick(anim._start + 50);
expect(target.value).toEqual(5);
anim.tick(anim._start + 100);
expect(target.value).toEqual(10);
anim.tick(anim._start + 150);
expect(target.value).toEqual(5);
anim.tick(anim._start + 400);
expect(target.value).toEqual(0);
});
it('should update', function() {
const target = {testColor: 'transparent'};
const anim = new Chart.Animation({duration: 100, type: 'color'}, target, 'testColor', 'red');
anim.tick(anim._start + 50);
expect(target.testColor).toEqual('#FF000080');
anim.update({duration: 500}, 'blue', Date.now());
anim.tick(anim._start + 250);
expect(target.testColor).toEqual('#4000BFBF');
anim.tick(anim._start + 500);
expect(target.testColor).toEqual('blue');
});
it('should not update when finished', function() {
const target = {testColor: 'transparent'};
const anim = new Chart.Animation({duration: 100, type: 'color'}, target, 'testColor', 'red');
anim.tick(anim._start + 100);
expect(target.testColor).toEqual('red');
expect(anim.active()).toBeFalse();
anim.update({duration: 500}, 'blue', Date.now());
expect(anim._duration).toEqual(100);
expect(anim._to).toEqual('red');
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/controller.scatter.tests.js | test/specs/controller.scatter.tests.js | describe('Chart.controllers.scatter', function() {
describe('auto', jasmine.fixture.specs('controller.scatter'));
it('should be registered as dataset controller', function() {
expect(typeof Chart.controllers.scatter).toBe('function');
});
it('should only show a single point in the tooltip on multiple datasets', async function() {
var chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{
x: 10,
y: 15
},
{
x: 12,
y: 10
}],
label: 'dataset1'
},
{
data: [{
x: 20,
y: 10
},
{
x: 4,
y: 8
}],
label: 'dataset2'
}]
},
options: {}
});
var point = chart.getDatasetMeta(0).data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(chart.tooltip.body.length).toEqual(1);
});
it('should not create line element by default', function() {
var chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{
x: 10,
y: 15
},
{
x: 12,
y: 10
}],
label: 'dataset1'
},
{
data: [{
x: 20,
y: 10
},
{
x: 4,
y: 8
}],
label: 'dataset2'
}]
},
});
var meta = chart.getDatasetMeta(0);
expect(meta.dataset instanceof Chart.elements.LineElement).toBe(false);
});
it('should create line element if showline is true at datasets options', function() {
var chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{
showLine: true,
data: [{
x: 10,
y: 15
},
{
x: 12,
y: 10
}],
label: 'dataset1'
},
{
data: [{
x: 20,
y: 10
},
{
x: 4,
y: 8
}],
label: 'dataset2'
}]
},
});
var meta = chart.getDatasetMeta(0);
expect(meta.dataset instanceof Chart.elements.LineElement).toBe(true);
});
it('should create line element if showline is true at root options', function() {
var chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{
data: [{
x: 10,
y: 15
},
{
x: 12,
y: 10
}],
label: 'dataset1'
},
{
data: [{
x: 20,
y: 10
},
{
x: 4,
y: 8
}],
label: 'dataset2'
}]
},
options: {
showLine: true
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.dataset instanceof Chart.elements.LineElement).toBe(true);
});
it('should not override tooltip title and label callbacks', async() => {
const chart = window.acquireChart({
type: 'scatter',
data: {
labels: ['Label 1', 'Label 2'],
datasets: [{
data: [{
x: 10,
y: 15
},
{
x: 12,
y: 10
}],
label: 'Dataset 1'
}, {
data: [{
x: 20,
y: 10
},
{
x: 4,
y: 8
}],
label: 'Dataset 2'
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
}
});
const {tooltip} = chart;
const point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Label 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Dataset 1: (10, 15)'],
after: []
}]);
chart.options.plugins.tooltip = {mode: 'dataset'};
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Dataset 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Label 1: (10, 15)'],
after: []
}, {
before: [],
lines: ['Label 2: (12, 10)'],
after: []
}]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.math.tests.js | test/specs/helpers.math.tests.js | const math = Chart.helpers;
describe('Chart.helpers.math', function() {
var factorize = math._factorize;
var decimalPlaces = math._decimalPlaces;
it('should factorize', function() {
expect(factorize(1000)).toEqual([1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 125, 200, 250, 500]);
expect(factorize(60)).toEqual([1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]);
expect(factorize(30)).toEqual([1, 2, 3, 5, 6, 10, 15]);
expect(factorize(24)).toEqual([1, 2, 3, 4, 6, 8, 12]);
expect(factorize(12)).toEqual([1, 2, 3, 4, 6]);
expect(factorize(4)).toEqual([1, 2]);
expect(factorize(-1)).toEqual([]);
expect(factorize(2.76)).toEqual([]);
});
it('should do a log10 operation', function() {
expect(math.log10(0)).toBe(-Infinity);
// Check all allowed powers of 10, which should return integer values
var maxPowerOf10 = Math.floor(math.log10(Number.MAX_VALUE));
for (var i = 0; i < maxPowerOf10; i += 1) {
expect(math.log10(Math.pow(10, i))).toBe(i);
}
});
it('should get the correct number of decimal places', function() {
expect(decimalPlaces(100)).toBe(0);
expect(decimalPlaces(1)).toBe(0);
expect(decimalPlaces(0)).toBe(0);
expect(decimalPlaces(0.01)).toBe(2);
expect(decimalPlaces(-0.01)).toBe(2);
expect(decimalPlaces('1')).toBe(undefined);
expect(decimalPlaces('')).toBe(undefined);
expect(decimalPlaces(undefined)).toBe(undefined);
expect(decimalPlaces(12345678.1234)).toBe(4);
expect(decimalPlaces(1234567890.1234567)).toBe(7);
});
it('should get an angle from a point', function() {
var center = {
x: 0,
y: 0
};
expect(math.getAngleFromPoint(center, {
x: 0,
y: 10
})).toEqual({
angle: Math.PI / 2,
distance: 10,
});
expect(math.getAngleFromPoint(center, {
x: Math.sqrt(2),
y: Math.sqrt(2)
})).toEqual({
angle: Math.PI / 4,
distance: 2
});
expect(math.getAngleFromPoint(center, {
x: -1.0 * Math.sqrt(2),
y: -1.0 * Math.sqrt(2)
})).toEqual({
angle: Math.PI * 1.25,
distance: 2
});
});
it('should convert between radians and degrees', function() {
expect(math.toRadians(180)).toBe(Math.PI);
expect(math.toRadians(90)).toBe(0.5 * Math.PI);
expect(math.toDegrees(Math.PI)).toBe(180);
expect(math.toDegrees(Math.PI * 3 / 2)).toBe(270);
});
it('should correctly determine if two numbers are essentially equal', function() {
expect(math.almostEquals(0, Number.EPSILON, 2 * Number.EPSILON)).toBe(true);
expect(math.almostEquals(1, 1.1, 0.0001)).toBe(false);
expect(math.almostEquals(1e30, 1e30 + Number.EPSILON, 0)).toBe(false);
expect(math.almostEquals(1e30, 1e30 + Number.EPSILON, 2 * Number.EPSILON)).toBe(true);
});
it('should get the correct sign', function() {
expect(math.sign(0)).toBe(0);
expect(math.sign(10)).toBe(1);
expect(math.sign(-5)).toBe(-1);
});
it('should correctly determine if a numbers are essentially whole', function() {
expect(math.almostWhole(0.99999, 0.0001)).toBe(true);
expect(math.almostWhole(0.9, 0.0001)).toBe(false);
expect(math.almostWhole(1234567890123, 0.0001)).toBe(true);
expect(math.almostWhole(1234567890123.001, 0.0001)).toBe(false);
});
it('should detect a number', function() {
expect(math.isNumber(123)).toBe(true);
expect(math.isNumber('123')).toBe(true);
expect(math.isNumber(null)).toBe(false);
expect(math.isNumber(NaN)).toBe(false);
expect(math.isNumber(undefined)).toBe(false);
expect(math.isNumber('cbc')).toBe(false);
expect(math.isNumber(Symbol())).toBe(false);
expect(math.isNumber(Object.create(null))).toBe(false);
});
it('should compute shortest distance between angles', function() {
expect(math._angleDiff(1, 2)).toEqual(-1);
expect(math._angleDiff(2, 1)).toEqual(1);
expect(math._angleDiff(0, 3.15)).toBeCloseTo(3.13, 2);
expect(math._angleDiff(0, 3.13)).toEqual(-3.13);
expect(math._angleDiff(6.2, 0)).toBeCloseTo(-0.08, 2);
expect(math._angleDiff(6.3, 0)).toBeCloseTo(0.02, 2);
expect(math._angleDiff(4 * Math.PI, -4 * Math.PI)).toBeCloseTo(0, 4);
expect(math._angleDiff(4 * Math.PI, -3 * Math.PI)).toBeCloseTo(-3.14, 2);
expect(math._angleDiff(6.28, 3.1)).toBeCloseTo(-3.1, 2);
expect(math._angleDiff(6.28, 3.2)).toBeCloseTo(3.08, 2);
});
it('should normalize angles correctly', function() {
expect(math._normalizeAngle(-Math.PI)).toEqual(Math.PI);
expect(math._normalizeAngle(Math.PI)).toEqual(Math.PI);
expect(math._normalizeAngle(2)).toEqual(2);
expect(math._normalizeAngle(5 * Math.PI)).toEqual(Math.PI);
expect(math._normalizeAngle(-50 * Math.PI)).toBeCloseTo(6.28, 2);
});
it('should determine if angle is between boundaries', function() {
expect(math._angleBetween(2, 1, 3)).toBeTrue();
expect(math._angleBetween(2, 3, 1)).toBeFalse();
expect(math._angleBetween(-3.14, 2, 4)).toBeTrue();
expect(math._angleBetween(-3.14, 4, 2)).toBeFalse();
expect(math._angleBetween(0, -1, 1)).toBeTrue();
expect(math._angleBetween(-1, 0, 1)).toBeFalse();
expect(math._angleBetween(-15 * Math.PI, 3.1, 3.2)).toBeTrue();
expect(math._angleBetween(15 * Math.PI, -3.2, -3.1)).toBeTrue();
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.dom.tests.js | test/specs/helpers.dom.tests.js | describe('DOM helpers tests', function() {
let helpers;
beforeAll(function() {
helpers = window.Chart.helpers;
});
it ('should get the maximum size for a node', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for
var innerDiv = document.createElement('div');
div.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({width: 200, height: 300}));
document.body.removeChild(div);
});
it ('should get the maximum width and height for a node in a ShadowRoot', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
if (!div.attachShadow) {
// Shadow DOM is not natively supported
return;
}
var shadow = div.attachShadow({mode: 'closed'});
// Create the div we want to get the max size for
var innerDiv = document.createElement('div');
shadow.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({width: 200, height: 300}));
document.body.removeChild(div);
});
it ('should get the maximum width of a node that has a max-width style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for and set a max-width style
var innerDiv = document.createElement('div');
innerDiv.style.maxWidth = '150px';
div.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({width: 150}));
document.body.removeChild(div);
});
it ('should get the maximum height of a node that has a max-height style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for and set a max-height style
var innerDiv = document.createElement('div');
innerDiv.style.maxHeight = '150px';
div.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({height: 150}));
document.body.removeChild(div);
});
it ('should get the maximum width of a node when the parent has a max-width style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create an inner wrapper around our div we want to size and give that a max-width style
var parentDiv = document.createElement('div');
parentDiv.style.maxWidth = '150px';
div.appendChild(parentDiv);
// Create the div we want to get the max size for
var innerDiv = document.createElement('div');
parentDiv.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({width: 150}));
document.body.removeChild(div);
});
it ('should get the maximum height of a node when the parent has a max-height style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create an inner wrapper around our div we want to size and give that a max-height style
var parentDiv = document.createElement('div');
parentDiv.style.maxHeight = '150px';
div.appendChild(parentDiv);
// Create the div we want to get the max size for
var innerDiv = document.createElement('div');
innerDiv.style.height = '300px'; // make it large
parentDiv.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({height: 150}));
document.body.removeChild(div);
});
it ('should get the maximum width of a node that has a percentage max-width style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for and set a max-width style
var innerDiv = document.createElement('div');
innerDiv.style.maxWidth = '50%';
div.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({width: 100}));
document.body.removeChild(div);
});
it('should get the maximum height of a node that has a percentage max-height style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create the div we want to get the max size for and set a max-height style
var innerDiv = document.createElement('div');
innerDiv.style.maxHeight = '50%';
div.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({height: 150}));
document.body.removeChild(div);
});
it ('should get the maximum width of a node when the parent has a percentage max-width style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create an inner wrapper around our div we want to size and give that a max-width style
var parentDiv = document.createElement('div');
parentDiv.style.maxWidth = '50%';
div.appendChild(parentDiv);
// Create the div we want to get the max size for
var innerDiv = document.createElement('div');
parentDiv.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({width: 100}));
document.body.removeChild(div);
});
it ('should get the maximum height of a node when the parent has a percentage max-height style', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '200px';
div.style.height = '300px';
document.body.appendChild(div);
// Create an inner wrapper around our div we want to size and give that a max-height style
var parentDiv = document.createElement('div');
parentDiv.style.maxHeight = '50%';
div.appendChild(parentDiv);
var innerDiv = document.createElement('div');
innerDiv.style.height = '300px'; // make it large
parentDiv.appendChild(innerDiv);
expect(helpers.getMaximumSize(innerDiv)).toEqual(jasmine.objectContaining({height: 150}));
document.body.removeChild(div);
});
it ('Should get padding of parent as number (pixels) when defined as percent (returns incorrectly in IE11)', function() {
// Create div with fixed size as a test bed
var div = document.createElement('div');
div.style.width = '300px';
div.style.height = '300px';
document.body.appendChild(div);
// Inner DIV to have 5% padding of parent
var innerDiv = document.createElement('div');
div.appendChild(innerDiv);
var canvas = document.createElement('canvas');
innerDiv.appendChild(canvas);
// No padding
expect(helpers.getMaximumSize(canvas)).toEqual(jasmine.objectContaining({width: 300}));
// test with percentage
innerDiv.style.padding = '5%';
expect(helpers.getMaximumSize(canvas)).toEqual(jasmine.objectContaining({width: 270}));
// test with pixels
innerDiv.style.padding = '10px';
expect(helpers.getMaximumSize(canvas)).toEqual(jasmine.objectContaining({width: 280}));
document.body.removeChild(div);
});
it ('should leave styled height and width on canvas if explicitly set', function() {
var chart = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
style: 'height: 400px; width: 400px;'
}
});
helpers.retinaScale(chart, true);
var canvas = chart.canvas;
expect(canvas.style.height).toBe('400px');
expect(canvas.style.width).toBe('400px');
});
it ('should handle devicePixelRatio correctly', function() {
const chartWidth = 800;
const chartHeight = 400;
let devicePixelRatio = 0.8999999761581421; // 1.7999999523162842;
var chart = window.acquireChart({}, {
canvas: {
width: chartWidth,
height: chartHeight,
}
});
helpers.retinaScale(chart, devicePixelRatio, true);
var canvas = chart.canvas;
expect(canvas.width).toBe(Math.round(chartWidth * devicePixelRatio));
expect(canvas.height).toBe(Math.round(chartHeight * devicePixelRatio));
expect(chart.width).toBe(chartWidth);
expect(chart.height).toBe(chartHeight);
expect(canvas.style.width).toBe(`${chartWidth}px`);
expect(canvas.style.height).toBe(`${chartHeight}px`);
});
describe('getRelativePosition', function() {
it('should use offsetX/Y when available', function() {
const event = {offsetX: 50, offsetY: 100};
const chart = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
}
});
expect(helpers.getRelativePosition(event, chart)).toEqual({x: 50, y: 100});
const chart2 = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
style: 'padding: 10px'
}
});
expect(helpers.getRelativePosition(event, chart2)).toEqual({
x: Math.round((event.offsetX - 10) / 180 * 200),
y: Math.round((event.offsetY - 10) / 180 * 200)
});
const chart3 = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
style: 'width: 400px, height: 400px; padding: 10px'
}
});
expect(helpers.getRelativePosition(event, chart3)).toEqual({
x: Math.round((event.offsetX - 10) / 360 * 400),
y: Math.round((event.offsetY - 10) / 360 * 400)
});
const chart4 = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
style: 'width: 400px, height: 400px; padding: 10px; position: absolute; left: 20, top: 20'
}
});
expect(helpers.getRelativePosition(event, chart4)).toEqual({
x: Math.round((event.offsetX - 10) / 360 * 400),
y: Math.round((event.offsetY - 10) / 360 * 400)
});
});
it('should calculate from clientX/Y as fallback', function() {
const chart = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
}
});
const event = {
clientX: 50,
clientY: 100
};
const rect = chart.canvas.getBoundingClientRect();
const pos = helpers.getRelativePosition(event, chart);
expect(Math.abs(pos.x - Math.round(event.clientX - rect.x))).toBeLessThanOrEqual(1);
expect(Math.abs(pos.y - Math.round(event.clientY - rect.y))).toBeLessThanOrEqual(1);
const chart2 = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
style: 'padding: 10px'
}
});
const rect2 = chart2.canvas.getBoundingClientRect();
const pos2 = helpers.getRelativePosition(event, chart2);
expect(Math.abs(pos2.x - Math.round((event.clientX - rect2.x - 10) / 180 * 200))).toBeLessThanOrEqual(1);
expect(Math.abs(pos2.y - Math.round((event.clientY - rect2.y - 10) / 180 * 200))).toBeLessThanOrEqual(1);
const chart3 = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
style: 'width: 400px, height: 400px; padding: 10px'
}
});
const rect3 = chart3.canvas.getBoundingClientRect();
const pos3 = helpers.getRelativePosition(event, chart3);
expect(Math.abs(pos3.x - Math.round((event.clientX - rect3.x - 10) / 360 * 400))).toBeLessThanOrEqual(1);
expect(Math.abs(pos3.y - Math.round((event.clientY - rect3.y - 10) / 360 * 400))).toBeLessThanOrEqual(1);
});
it ('should get the correct relative position for a node in a ShadowRoot', function() {
const event = {
offsetX: 50,
offsetY: 100,
clientX: 50,
clientY: 100
};
const chart = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
},
useShadowDOM: true
});
event.target = chart.canvas.parentNode.host;
expect(event.target.shadowRoot).not.toEqual(null);
const rect = chart.canvas.getBoundingClientRect();
const pos = helpers.getRelativePosition(event, chart);
expect(Math.abs(pos.x - Math.round(event.clientX - rect.x))).toBeLessThanOrEqual(1);
expect(Math.abs(pos.y - Math.round(event.clientY - rect.y))).toBeLessThanOrEqual(1);
const chart2 = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
style: 'padding: 10px'
},
useShadowDOM: true
});
event.target = chart2.canvas.parentNode.host;
const rect2 = chart2.canvas.getBoundingClientRect();
const pos2 = helpers.getRelativePosition(event, chart2);
expect(Math.abs(pos2.x - Math.round((event.clientX - rect2.x - 10) / 180 * 200))).toBeLessThanOrEqual(1);
expect(Math.abs(pos2.y - Math.round((event.clientY - rect2.y - 10) / 180 * 200))).toBeLessThanOrEqual(1);
const chart3 = window.acquireChart({}, {
canvas: {
height: 200,
width: 200,
style: 'width: 400px, height: 400px; padding: 10px'
},
useShadowDOM: true
});
event.target = chart3.canvas.parentNode.host;
const rect3 = chart3.canvas.getBoundingClientRect();
const pos3 = helpers.getRelativePosition(event, chart3);
expect(Math.abs(pos3.x - Math.round((event.clientX - rect3.x - 10) / 360 * 400))).toBeLessThanOrEqual(1);
expect(Math.abs(pos3.y - Math.round((event.clientY - rect3.y - 10) / 360 * 400))).toBeLessThanOrEqual(1);
});
it('Should not return NaN with a custom event', async function() {
let dataX = null;
let dataY = null;
const chart = window.acquireChart(
{
type: 'bar',
data: {
datasets: [{
data: [{x: 'first', y: 10}, {x: 'second', y: 5}, {x: 'third', y: 15}]
}]
},
options: {
onHover: (e) => {
const canvasPosition = Chart.helpers.getRelativePosition(e, chart);
dataX = canvasPosition.x;
dataY = canvasPosition.y;
}
}
});
const point = chart.getDatasetMeta(0).data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(dataX).not.toEqual(NaN);
expect(dataY).not.toEqual(NaN);
});
it('Should give consistent results for native and chart events', async function() {
let chartPosition = null;
const chart = window.acquireChart(
{
type: 'bar',
data: {
datasets: [{
data: [{x: 'first', y: 10}, {x: 'second', y: 5}, {x: 'third', y: 15}]
}]
},
options: {
onHover: (chartEvent) => {
chartPosition = Chart.helpers.getRelativePosition(chartEvent, chart);
}
}
});
const point = chart.getDatasetMeta(0).data[1];
const nativeEvent = await jasmine.triggerMouseEvent(chart, 'mousemove', point);
const nativePosition = Chart.helpers.getRelativePosition(nativeEvent, chart);
expect(chartPosition).not.toBeNull();
expect(nativePosition).toEqual({x: chartPosition.x, y: chartPosition.y});
});
});
it('should respect aspect ratio and container width', () => {
const container = document.createElement('div');
container.style.width = '200px';
container.style.height = '500px';
document.body.appendChild(container);
const target = document.createElement('div');
target.style.width = '500px';
target.style.height = '500px';
container.appendChild(target);
expect(helpers.getMaximumSize(target, 200, 500, 1)).toEqual(jasmine.objectContaining({width: 200, height: 200}));
document.body.removeChild(container);
});
it('should respect aspect ratio and container height', () => {
const container = document.createElement('div');
container.style.width = '500px';
container.style.height = '200px';
document.body.appendChild(container);
const target = document.createElement('div');
target.style.width = '500px';
target.style.height = '500px';
container.appendChild(target);
expect(helpers.getMaximumSize(target, 500, 200, 1)).toEqual(jasmine.objectContaining({width: 200, height: 200}));
document.body.removeChild(container);
});
it('should respect aspect ratio and skip container height', () => {
const container = document.createElement('div');
container.style.width = '500px';
container.style.height = '200px';
document.body.appendChild(container);
const target = document.createElement('div');
target.style.width = '500px';
target.style.height = '500px';
container.appendChild(target);
expect(helpers.getMaximumSize(target, undefined, undefined, 1)).toEqual(jasmine.objectContaining({width: 500, height: 500}));
document.body.removeChild(container);
});
it('should round non-integer container dimensions', () => {
const container = document.createElement('div');
container.style.width = '799.999px';
container.style.height = '299.999px';
document.body.appendChild(container);
const target = document.createElement('div');
target.style.width = '200px';
target.style.height = '100px';
container.appendChild(target);
expect(helpers.getMaximumSize(target, undefined, undefined, 2)).toEqual(jasmine.objectContaining({width: 800, height: 400}));
document.body.removeChild(container);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.interaction.tests.js | test/specs/core.interaction.tests.js | describe('Core.Interaction', function() {
describe('auto', jasmine.fixture.specs('core.interaction'));
describe('point mode', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 20, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
}
});
});
it ('should return all items under the point', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
var point = meta0.data[1];
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: point.x,
y: point.y,
};
var elements = Chart.Interaction.modes.point(chart, evt, {}).map(item => item.element);
expect(elements).toEqual([point, meta1.data[1]]);
});
it ('should return an empty array when no items are found', function() {
var chart = this.chart;
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: 0,
y: 0
};
var elements = Chart.Interaction.modes.point(chart, evt, {}).map(item => item.element);
expect(elements).toEqual([]);
});
});
describe('index mode', function() {
describe('intersect: true', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
}
});
});
it ('gets correct items', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
var point = meta0.data[1];
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: point.x,
y: point.y,
};
var elements = Chart.Interaction.modes.index(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([point, meta1.data[1]]);
});
it ('returns empty array when nothing found', function() {
var chart = this.chart;
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: 0,
y: 0,
};
var elements = Chart.Interaction.modes.index(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([]);
});
});
describe ('intersect: false', function() {
var data = {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
};
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: data
});
});
it ('axis: x gets correct items', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: chart.chartArea.left,
y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.index(chart, evt, {intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[0], meta1.data[0]]);
});
it ('axis: y gets correct items', function() {
var chart = window.acquireChart({
type: 'bar',
data: data,
options: {
indexAxis: 'y',
}
});
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
var center = meta0.data[0].getCenterPoint();
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: center.x,
y: center.y + 30,
};
var elements = Chart.Interaction.modes.index(chart, evt, {axis: 'y', intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[0], meta1.data[0]]);
});
it ('axis: xy gets correct items', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: chart.chartArea.left,
y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.index(chart, evt, {axis: 'xy', intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[0], meta1.data[0]]);
});
});
});
describe('dataset mode', function() {
describe('intersect: true', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
}
});
});
it ('should return all items in the dataset of the first item found', function() {
var chart = this.chart;
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: point.x,
y: point.y
};
var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual(meta.data);
});
it ('should return an empty array if nothing found', function() {
var chart = this.chart;
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: 0,
y: 0
};
var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: true});
expect(elements).toEqual([]);
});
});
describe('intersect: false', function() {
var data = {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
};
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: data
});
});
it ('axis: x gets correct items', function() {
var chart = window.acquireChart({
type: 'bar',
data: data,
options: {
indexAxis: 'y',
}
});
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: chart.chartArea.left,
y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'x', intersect: false}).map(item => item.element);
expect(elements).toEqual(chart.getDatasetMeta(0).data);
});
it ('axis: y gets correct items', function() {
var chart = this.chart;
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: chart.chartArea.left,
y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'y', intersect: false}).map(item => item.element);
expect(elements).toEqual(chart.getDatasetMeta(1).data);
});
it ('axis: xy gets correct items', function() {
var chart = this.chart;
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: chart.chartArea.left,
y: chart.chartArea.top
};
var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: false}).map(item => item.element);
expect(elements).toEqual(chart.getDatasetMeta(1).data);
});
});
});
describe('nearest mode', function() {
describe('intersect: false', function() {
beforeEach(function() {
this.lineChart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 40, 30],
pointRadius: [5, 5, 5],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointRadius: [10, 10, 10],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
}
});
this.polarChart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [{
data: [1, 9, 5]
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
legend: {
display: false
},
},
}
});
});
describe('axis: xy', function() {
it ('should return the nearest item', function() {
var chart = this.lineChart;
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: chart.chartArea.left,
y: chart.chartArea.top
};
// Nearest to 0,0 (top left) will be first point of dataset 2
var elements = Chart.Interaction.modes.nearest(chart, evt, {intersect: false}).map(item => item.element);
var meta = chart.getDatasetMeta(1);
expect(elements).toEqual([meta.data[0]]);
});
it ('should return all items at the same nearest distance', function() {
var chart = this.lineChart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// Halfway between 2 mid points
var pt = {
x: meta0.data[1].x,
y: (meta0.data[1].y + meta1.data[1].y) / 2
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: pt.y
};
// Both points are nearest
var elements = Chart.Interaction.modes.nearest(chart, evt, {intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[1], meta1.data[1]]);
});
});
describe('axis: x', function() {
it ('should return all items at current x', function() {
var chart = this.lineChart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// At 'Point 2', 10
var pt = {
x: meta0.data[1].x,
y: meta0.data[0].y
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: pt.y
};
// Middle point from both series are nearest
var elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'x', intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[1], meta1.data[1]]);
});
it ('should return all items at nearest x-distance', function() {
var chart = this.lineChart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// Haflway between 'Point 1' and 'Point 2', y=10
var pt = {
x: (meta0.data[0].x + meta0.data[1].x) / 2,
y: meta0.data[0].y
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: pt.y
};
// Should return all (4) points from 'Point 1' and 'Point 2'
var elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'x', intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[0], meta0.data[1], meta1.data[0], meta1.data[1]]);
});
});
describe('axis: y', function() {
it ('should return item with value 30', function() {
var chart = this.lineChart;
var meta0 = chart.getDatasetMeta(0);
// 'Point 1', y = 30
var pt = {
x: meta0.data[0].x,
y: meta0.data[2].y
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: pt.y
};
// Middle point from both series are nearest
var elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'y', intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[2]]);
});
it ('should return all items at value 40', function() {
var chart = this.lineChart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// 'Point 1', y = 40
var pt = {
x: meta0.data[0].x,
y: meta0.data[1].y
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: pt.y
};
// Should return points with value 40
var elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'y', intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[1], meta1.data[0], meta1.data[1], meta1.data[2]]);
});
});
describe('axis: r', function() {
it ('should return item with value 9', function() {
var chart = this.polarChart;
var meta0 = chart.getDatasetMeta(0);
var evt = {
type: 'click',
chart: chart,
native: true, // Needed, otherwise assumed to be a DOM event
x: chart.width / 2,
y: chart.height / 2 + 5,
};
var elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'r'}).map(item => item.element);
expect(elements).toEqual([meta0.data[1]]);
});
it ('should return item with value 1 when clicked outside of it', function() {
var chart = this.polarChart;
var meta0 = chart.getDatasetMeta(0);
var evt = {
type: 'click',
chart: chart,
native: true, // Needed, otherwise assumed to be a DOM event
x: chart.width,
y: 0,
};
var elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'r', intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[0]]);
});
});
});
describe('intersect: true', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
}
});
});
describe('axis=xy', function() {
it ('should return the nearest item', function() {
var chart = this.chart;
var meta = chart.getDatasetMeta(1);
var point = meta.data[1];
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: point.x + 15,
y: point.y
};
// Nothing intersects so find nothing
var elements = Chart.Interaction.modes.nearest(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([]);
evt = {
type: 'click',
chart: chart,
native: true,
x: point.x,
y: point.y
};
elements = Chart.Interaction.modes.nearest(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([point]);
});
it ('should return the nearest item even if 2 intersect', function() {
var chart = this.chart;
chart.data.datasets[0].pointRadius = [5, 30, 5];
chart.data.datasets[0].data[1] = 39;
chart.data.datasets[1].pointRadius = [10, 10, 10];
chart.update();
// Trigger an event over top of the
var meta0 = chart.getDatasetMeta(0);
// Halfway between 2 mid points
var pt = {
x: meta0.data[1].x,
y: meta0.data[1].y
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: pt.y
};
var elements = Chart.Interaction.modes.nearest(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([meta0.data[1]]);
});
it ('should return the all items if more than 1 are at the same distance', function() {
var chart = this.chart;
chart.data.datasets[0].pointRadius = [5, 5, 5];
chart.data.datasets[0].data[1] = 40;
chart.data.datasets[1].pointRadius = [10, 10, 10];
chart.update();
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// Halfway between 2 mid points
var pt = {
x: meta0.data[1].x,
y: meta0.data[1].y
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: pt.y
};
var elements = Chart.Interaction.modes.nearest(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([meta0.data[1], meta1.data[1]]);
});
});
});
});
describe('x mode', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 40, 30],
pointRadius: [5, 10, 5],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointRadius: [10, 10, 10],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
}
});
});
it('should return items at the same x value when intersect is false', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// Halfway between 2 mid points
var pt = {
x: meta0.data[1].x,
y: meta0.data[1].y
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: 0
};
var elements = Chart.Interaction.modes.x(chart, evt, {intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[1], meta1.data[1]]);
evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x + 20,
y: 0
};
elements = Chart.Interaction.modes.x(chart, evt, {intersect: false}).map(item => item.element);
expect(elements).toEqual([]);
});
it('should return items at the same x value when intersect is true', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// Halfway between 2 mid points
var pt = {
x: meta0.data[1].x,
y: meta0.data[1].y
};
var evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: 0
};
var elements = Chart.Interaction.modes.x(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([]); // we don't intersect anything
evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: pt.x,
y: pt.y
};
elements = Chart.Interaction.modes.x(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([meta0.data[1], meta1.data[1]]);
});
});
describe('y mode', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 40, 30],
pointRadius: [5, 10, 5],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointRadius: [10, 10, 10],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
}
});
});
it('should return items at the same y value when intersect is false', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// Halfway between 2 mid points
var pt = {
x: meta0.data[1].x,
y: meta0.data[1].y
};
var evt = {
type: 'click',
chart: chart,
native: true,
x: 0,
y: pt.y,
};
var elements = Chart.Interaction.modes.y(chart, evt, {intersect: false}).map(item => item.element);
expect(elements).toEqual([meta0.data[1], meta1.data[0], meta1.data[1], meta1.data[2]]);
evt = {
type: 'click',
chart: chart,
native: true,
x: pt.x,
y: pt.y + 20, // out of range
};
elements = Chart.Interaction.modes.y(chart, evt, {intersect: false}).map(item => item.element);
expect(elements).toEqual([]);
});
it('should return items at the same y value when intersect is true', function() {
var chart = this.chart;
var meta0 = chart.getDatasetMeta(0);
var meta1 = chart.getDatasetMeta(1);
// Halfway between 2 mid points
var pt = {
x: meta0.data[1].x,
y: meta0.data[1].y
};
var evt = {
type: 'click',
chart: chart,
native: true,
x: 0,
y: pt.y
};
var elements = Chart.Interaction.modes.y(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([]); // we don't intersect anything
evt = {
type: 'click',
chart: chart,
native: true,
x: pt.x,
y: pt.y,
};
elements = Chart.Interaction.modes.y(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).toEqual([meta0.data[1], meta1.data[0], meta1.data[1], meta1.data[2]]);
});
});
describe('tooltip element of scatter chart', function() {
it ('out-of-range datapoints are not shown in tooltip', function() {
let data = [];
for (let i = 0; i < 1000; i++) {
data.push({x: i, y: i});
}
const chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{data}]
},
options: {
scales: {
x: {
min: 2
}
}
}
});
const meta0 = chart.getDatasetMeta(0);
const firstElement = meta0.data[0];
const evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: firstElement.x,
y: firstElement.y
};
const elements = Chart.Interaction.modes.point(chart, evt, {intersect: true}).map(item => item.element);
expect(elements).not.toContain(firstElement);
});
it ('out-of-range datapoints are shown in tooltip if included', function() {
let data = [];
for (let i = 0; i < 1000; i++) {
data.push({x: i, y: i});
}
const chart = window.acquireChart({
type: 'scatter',
data: {
datasets: [{data}]
},
options: {
scales: {
x: {
min: 2
}
}
}
});
const meta0 = chart.getDatasetMeta(0);
const firstElement = meta0.data[0];
const evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise it thinks its a DOM event
x: firstElement.x,
y: firstElement.y
};
const elements = Chart.Interaction.modes.point(
chart,
evt,
{
intersect: true,
includeInvisible: true
}).map(item => item.element);
expect(elements).toContain(firstElement);
});
});
const testCases = [
{
data: [12, 19, null, null, null, null, 5, 2],
clickPointIndex: 0,
expectedNearestPointIndex: 0
},
{
data: [12, 19, null, null, null, null, 5, 2],
clickPointIndex: 1,
expectedNearestPointIndex: 1},
{
data: [12, 19, null, null, null, null, 5, 2],
clickPointIndex: 2,
expectedNearestPointIndex: 1
},
{
data: [12, 19, null, null, null, null, 5, 2],
clickPointIndex: 3,
expectedNearestPointIndex: 1
},
{
data: [12, 19, null, null, null, null, 5, 2],
clickPointIndex: 4,
expectedNearestPointIndex: 6
},
{
data: [12, 19, null, null, null, null, 5, 2],
clickPointIndex: 5,
expectedNearestPointIndex: 6
},
{
data: [12, 19, null, null, null, null, 5, 2],
clickPointIndex: 6,
expectedNearestPointIndex: 6
},
{
data: [12, 19, null, null, null, null, 5, 2],
clickPointIndex: 7,
expectedNearestPointIndex: 7
},
{
data: [12, 0, null, null, null, null, 0, 2],
clickPointIndex: 3,
expectedNearestPointIndex: 1
},
{
data: [12, 0, null, null, null, null, 0, 2],
clickPointIndex: 4,
expectedNearestPointIndex: 6
},
{
data: [12, -1, null, null, null, null, -1, 2],
clickPointIndex: 3,
expectedNearestPointIndex: 1
},
{
data: [12, -1, null, null, null, null, -1, 2],
clickPointIndex: 4,
expectedNearestPointIndex: 6
},
{
data: [null, 2],
clickPointIndex: 0,
expectedNearestPointIndex: 1
},
{
data: [2, null],
clickPointIndex: 1,
expectedNearestPointIndex: 0
},
{
data: [null, null, 2],
clickPointIndex: 0,
expectedNearestPointIndex: 2
},
{
data: [2, null, null],
clickPointIndex: 2,
expectedNearestPointIndex: 0
}
];
testCases.forEach(({data, clickPointIndex, expectedNearestPointIndex}, i) => {
it(`should select nearest non-null element with index ${expectedNearestPointIndex} when clicking on element with index ${clickPointIndex} in test case ${i + 1} if spanGaps=true`, function() {
const chart = window.acquireChart({
type: 'line',
data: {
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9],
datasets: [{
data: data,
spanGaps: true,
}]
}
});
chart.update();
const meta = chart.getDatasetMeta(0);
const point = meta.data[clickPointIndex];
const evt = {
type: 'click',
chart: chart,
native: true, // needed otherwise things its a DOM event
x: point.x,
y: point.y,
};
const elements = Chart.Interaction.modes.nearest(chart, evt, {axis: 'x', intersect: false}).map(item => item.element);
expect(elements).toEqual([meta.data[expectedNearestPointIndex]]);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.options.tests.js | test/specs/helpers.options.tests.js | const {toLineHeight, toPadding, toFont, resolve, toTRBLCorners} = Chart.helpers;
describe('Chart.helpers.options', function() {
describe('toLineHeight', function() {
it ('should support keyword values', function() {
expect(toLineHeight('normal', 16)).toBe(16 * 1.2);
});
it ('should support unitless values', function() {
expect(toLineHeight(1.4, 16)).toBe(16 * 1.4);
expect(toLineHeight('1.4', 16)).toBe(16 * 1.4);
});
it ('should support length values', function() {
expect(toLineHeight('42px', 16)).toBe(42);
expect(toLineHeight('1.4em', 16)).toBe(16 * 1.4);
});
it ('should support percentage values', function() {
expect(toLineHeight('140%', 16)).toBe(16 * 1.4);
});
it ('should fallback to default (1.2) for invalid values', function() {
expect(toLineHeight(null, 16)).toBe(16 * 1.2);
expect(toLineHeight(undefined, 16)).toBe(16 * 1.2);
expect(toLineHeight('foobar', 16)).toBe(16 * 1.2);
});
});
describe('toTRBLCorners', function() {
it('should support number values', function() {
expect(toTRBLCorners(4)).toEqual(
{topLeft: 4, topRight: 4, bottomLeft: 4, bottomRight: 4});
expect(toTRBLCorners(4.5)).toEqual(
{topLeft: 4.5, topRight: 4.5, bottomLeft: 4.5, bottomRight: 4.5});
});
it('should support string values', function() {
expect(toTRBLCorners('4')).toEqual(
{topLeft: 4, topRight: 4, bottomLeft: 4, bottomRight: 4});
expect(toTRBLCorners('4.5')).toEqual(
{topLeft: 4.5, topRight: 4.5, bottomLeft: 4.5, bottomRight: 4.5});
});
it('should support object values', function() {
expect(toTRBLCorners({topLeft: 1, topRight: 2, bottomLeft: 3, bottomRight: 4})).toEqual(
{topLeft: 1, topRight: 2, bottomLeft: 3, bottomRight: 4});
expect(toTRBLCorners({topLeft: 1.5, topRight: 2.5, bottomLeft: 3.5, bottomRight: 4.5})).toEqual(
{topLeft: 1.5, topRight: 2.5, bottomLeft: 3.5, bottomRight: 4.5});
expect(toTRBLCorners({topLeft: '1', topRight: '2', bottomLeft: '3', bottomRight: '4'})).toEqual(
{topLeft: 1, topRight: 2, bottomLeft: 3, bottomRight: 4});
});
it('should fallback to 0 for invalid values', function() {
expect(toTRBLCorners({topLeft: 'foo', topRight: 'foo', bottomLeft: 'foo', bottomRight: 'foo'})).toEqual(
{topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0});
expect(toTRBLCorners({topLeft: null, topRight: null, bottomLeft: null, bottomRight: null})).toEqual(
{topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0});
expect(toTRBLCorners({})).toEqual(
{topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0});
expect(toTRBLCorners('foo')).toEqual(
{topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0});
expect(toTRBLCorners(null)).toEqual(
{topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0});
expect(toTRBLCorners(undefined)).toEqual(
{topLeft: 0, topRight: 0, bottomLeft: 0, bottomRight: 0});
});
});
describe('toPadding', function() {
it ('should support number values', function() {
expect(toPadding(4)).toEqual(
{top: 4, right: 4, bottom: 4, left: 4, height: 8, width: 8});
expect(toPadding(4.5)).toEqual(
{top: 4.5, right: 4.5, bottom: 4.5, left: 4.5, height: 9, width: 9});
});
it ('should support string values', function() {
expect(toPadding('4')).toEqual(
{top: 4, right: 4, bottom: 4, left: 4, height: 8, width: 8});
expect(toPadding('4.5')).toEqual(
{top: 4.5, right: 4.5, bottom: 4.5, left: 4.5, height: 9, width: 9});
});
it ('should support object values', function() {
expect(toPadding({top: 1, right: 2, bottom: 3, left: 4})).toEqual(
{top: 1, right: 2, bottom: 3, left: 4, height: 4, width: 6});
expect(toPadding({top: 1.5, right: 2.5, bottom: 3.5, left: 4.5})).toEqual(
{top: 1.5, right: 2.5, bottom: 3.5, left: 4.5, height: 5, width: 7});
expect(toPadding({top: '1', right: '2', bottom: '3', left: '4'})).toEqual(
{top: 1, right: 2, bottom: 3, left: 4, height: 4, width: 6});
});
it ('should fallback to 0 for invalid values', function() {
expect(toPadding({top: 'foo', right: 'foo', bottom: 'foo', left: 'foo'})).toEqual(
{top: 0, right: 0, bottom: 0, left: 0, height: 0, width: 0});
expect(toPadding({top: null, right: null, bottom: null, left: null})).toEqual(
{top: 0, right: 0, bottom: 0, left: 0, height: 0, width: 0});
expect(toPadding({})).toEqual(
{top: 0, right: 0, bottom: 0, left: 0, height: 0, width: 0});
expect(toPadding('foo')).toEqual(
{top: 0, right: 0, bottom: 0, left: 0, height: 0, width: 0});
expect(toPadding(null)).toEqual(
{top: 0, right: 0, bottom: 0, left: 0, height: 0, width: 0});
expect(toPadding(undefined)).toEqual(
{top: 0, right: 0, bottom: 0, left: 0, height: 0, width: 0});
});
it('should support x / y shorthands', function() {
expect(toPadding({x: 1, y: 2})).toEqual(
{top: 2, right: 1, bottom: 2, left: 1, height: 4, width: 2});
expect(toPadding({x: 1, left: 0})).toEqual(
{top: 0, right: 1, bottom: 0, left: 0, height: 0, width: 1});
expect(toPadding({y: 5, bottom: 0})).toEqual(
{top: 5, right: 0, bottom: 0, left: 0, height: 5, width: 0});
});
});
describe('toFont', function() {
it('should return a font with default values', function() {
const defaultFont = Object.assign({}, Chart.defaults.font);
Object.assign(Chart.defaults.font, {
family: 'foobar',
size: 42,
style: 'oblique 9deg',
lineHeight: 1.5
});
expect(toFont({})).toEqual({
family: 'foobar',
lineHeight: 63,
size: 42,
string: 'oblique 9deg 42px foobar',
style: 'oblique 9deg',
weight: null
});
Object.assign(Chart.defaults.font, defaultFont);
});
it ('should return a font with given values', function() {
expect(toFont({
family: 'bla',
lineHeight: 8,
size: 21,
style: 'oblique -90deg'
})).toEqual({
family: 'bla',
lineHeight: 8 * 21,
size: 21,
string: 'oblique -90deg 21px bla',
style: 'oblique -90deg',
weight: null
});
});
it ('should handle a string font size', function() {
expect(toFont({
family: 'bla',
lineHeight: 8,
size: '21',
style: 'italic'
})).toEqual({
family: 'bla',
lineHeight: 8 * 21,
size: 21,
string: 'italic 21px bla',
style: 'italic',
weight: null
});
});
it('should return null as a font string if size or family are missing', function() {
const fontFamily = Chart.defaults.font.family;
const fontSize = Chart.defaults.font.size;
delete Chart.defaults.font.family;
delete Chart.defaults.font.size;
expect(toFont({
style: 'italic',
size: 12
}).string).toBeNull();
expect(toFont({
style: 'italic',
family: 'serif'
}).string).toBeNull();
Chart.defaults.font.family = fontFamily;
Chart.defaults.font.size = fontSize;
});
it('font.style should be optional for font strings', function() {
const fontStyle = Chart.defaults.font.style;
delete Chart.defaults.font.style;
expect(toFont({
size: 12,
family: 'serif'
}).string).toBe('12px serif');
Chart.defaults.font.style = fontStyle;
});
});
describe('resolve', function() {
it ('should fallback to the first defined input', function() {
expect(resolve([42])).toBe(42);
expect(resolve([42, 'foo'])).toBe(42);
expect(resolve([undefined, 42, 'foo'])).toBe(42);
expect(resolve([42, 'foo', undefined])).toBe(42);
expect(resolve([undefined])).toBe(undefined);
});
it ('should correctly handle empty values (null, 0, "")', function() {
expect(resolve([0, 'foo'])).toBe(0);
expect(resolve(['', 'foo'])).toBe('');
expect(resolve([null, 'foo'])).toBe(null);
});
it ('should support indexable options if index is provided', function() {
var input = [42, 'foo', 'bar'];
expect(resolve([input], undefined, 0)).toBe(42);
expect(resolve([input], undefined, 1)).toBe('foo');
expect(resolve([input], undefined, 2)).toBe('bar');
});
it ('should fallback if an indexable option value is undefined', function() {
var input = [42, undefined, 'bar'];
expect(resolve([input], undefined, 1)).toBe(undefined);
expect(resolve([input, 'foo'], undefined, 1)).toBe('foo');
});
it ('should loop if an indexable option index is out of bounds', function() {
var input = [42, undefined, 'bar'];
expect(resolve([input], undefined, 3)).toBe(42);
expect(resolve([input, 'foo'], undefined, 4)).toBe('foo');
expect(resolve([input, 'foo'], undefined, 5)).toBe('bar');
});
it ('should not handle indexable options if index is undefined', function() {
var array = [42, 'foo', 'bar'];
expect(resolve([array])).toBe(array);
expect(resolve([array], undefined, undefined)).toBe(array);
});
it ('should support scriptable options if context is provided', function() {
var input = function(context) {
return context.v * 2;
};
expect(resolve([42], {v: 42})).toBe(42);
expect(resolve([input], {v: 42})).toBe(84);
});
it ('should fallback if a scriptable option returns undefined', function() {
var input = function() {};
expect(resolve([input], {v: 42})).toBe(undefined);
expect(resolve([input, 'foo'], {v: 42})).toBe('foo');
expect(resolve([input, undefined, 'foo'], {v: 42})).toBe('foo');
});
it ('should not handle scriptable options if context is undefined', function() {
var input = function(context) {
return context.v * 2;
};
expect(resolve([input])).toBe(input);
expect(resolve([input], undefined)).toBe(input);
});
it ('should handle scriptable and indexable option', function() {
var input = function(context) {
return [context.v, undefined, 'bar'];
};
expect(resolve([input, 'foo'], {v: 42}, 0)).toBe(42);
expect(resolve([input, 'foo'], {v: 42}, 1)).toBe('foo');
expect(resolve([input, 'foo'], {v: 42}, 5)).toBe('bar');
expect(resolve([input, ['foo', 'bar']], {v: 42}, 1)).toBe('bar');
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/plugin.tooltip.tests.js | test/specs/plugin.tooltip.tests.js | // Test the rectangle element
const tooltipPlugin = Chart.registry.getPlugin('tooltip');
const Tooltip = tooltipPlugin._element;
describe('Plugin.Tooltip', function() {
describe('auto', jasmine.fixture.specs('plugin.tooltip'));
describe('config', function() {
it('should not include the dataset label in the body string if not defined', function() {
var data = {
datasets: [{
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
};
var tooltipItem = {
index: 1,
datasetIndex: 0,
dataset: data.datasets[0],
label: 'Point 2',
formattedValue: '20'
};
var label = Chart.defaults.plugins.tooltip.callbacks.label(tooltipItem);
expect(label).toBe('20');
data.datasets[0].label = 'My dataset';
label = Chart.defaults.plugins.tooltip.callbacks.label(tooltipItem);
expect(label).toBe('My dataset: 20');
});
});
describe('index mode', function() {
it('Should only use x distance when intersect is false', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'index',
intersect: false,
padding: {
left: 6,
top: 6,
right: 6,
bottom: 6
}
}
},
hover: {
mode: 'index',
intersect: false
}
}
});
// Trigger an event over top of the
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
var defaults = Chart.defaults;
await jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: chart.chartArea.top + 10});
expect(tooltip.options.padding).toEqualOptions({
left: 6,
top: 6,
right: 6,
bottom: 6,
});
expect(tooltip.xAlign).toEqual('left');
expect(tooltip.yAlign).toEqual('center');
expect(tooltip.options.bodyColor).toEqual('#fff');
expect(tooltip.options.bodyFont).toEqualOptions({
family: defaults.font.family,
style: defaults.font.style,
size: defaults.font.size,
});
expect(tooltip.options).toEqualOptions({
bodyAlign: 'left',
bodySpacing: 2,
});
expect(tooltip.options.titleColor).toEqual('#fff');
expect(tooltip.options.titleFont).toEqualOptions({
family: defaults.font.family,
weight: 'bold',
size: defaults.font.size,
});
expect(tooltip.options).toEqualOptions({
titleAlign: 'left',
titleSpacing: 2,
titleMarginBottom: 6,
});
expect(tooltip.options.footerColor).toEqual('#fff');
expect(tooltip.options.footerFont).toEqualOptions({
family: defaults.font.family,
weight: 'bold',
size: defaults.font.size,
});
expect(tooltip.options).toEqualOptions({
footerAlign: 'left',
footerSpacing: 2,
footerMarginTop: 6,
});
expect(tooltip.options).toEqualOptions({
// Appearance
caretSize: 5,
caretPadding: 2,
cornerRadius: 6,
backgroundColor: 'rgba(0,0,0,0.8)',
multiKeyBackground: '#fff',
displayColors: true
});
expect(tooltip).toEqual(jasmine.objectContaining({
opacity: 1,
// Text
title: ['Point 2'],
beforeBody: [],
body: [{
before: [],
lines: ['Dataset 1: 20'],
after: []
}, {
before: [],
lines: ['Dataset 2: 40'],
after: []
}],
afterBody: [],
footer: [],
labelColors: [{
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}, {
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}]
}));
expect(tooltip.x).toBeCloseToPixel(266);
expect(tooltip.y).toBeCloseToPixel(150);
});
it('Should only display if intersecting if intersect is set', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'index',
intersect: true
}
}
}
});
// Trigger an event over top of the
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', {x: point.x, y: 0});
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
expect(tooltip).toEqual(jasmine.objectContaining({
opacity: 0,
}));
});
});
it('Should display in single mode', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'nearest',
intersect: true
}
}
}
});
// Trigger an event over top of the
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
var defaults = Chart.defaults;
expect(tooltip.options.padding).toEqual(6);
expect(tooltip.xAlign).toEqual('left');
expect(tooltip.yAlign).toEqual('center');
expect(tooltip.options.bodyFont).toEqual(jasmine.objectContaining({
family: defaults.font.family,
style: defaults.font.style,
size: defaults.font.size,
}));
expect(tooltip.options).toEqualOptions({
bodyAlign: 'left',
bodySpacing: 2,
});
expect(tooltip.options.titleFont).toEqual(jasmine.objectContaining({
family: defaults.font.family,
weight: 'bold',
size: defaults.font.size,
}));
expect(tooltip.options).toEqualOptions({
titleAlign: 'left',
titleSpacing: 2,
titleMarginBottom: 6,
});
expect(tooltip.options.footerFont).toEqualOptions({
family: defaults.font.family,
weight: 'bold',
size: defaults.font.size,
});
expect(tooltip.options).toEqualOptions({
footerAlign: 'left',
footerSpacing: 2,
footerMarginTop: 6,
});
expect(tooltip.options).toEqualOptions({
// Appearance
caretSize: 5,
caretPadding: 2,
cornerRadius: 6,
backgroundColor: 'rgba(0,0,0,0.8)',
multiKeyBackground: '#fff',
displayColors: true
});
expect(tooltip.opacity).toEqual(1);
expect(tooltip.title).toEqual(['Point 2']);
expect(tooltip.beforeBody).toEqual([]);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Dataset 1: 20'],
after: []
}]);
expect(tooltip.afterBody).toEqual([]);
expect(tooltip.footer).toEqual([]);
expect(tooltip.labelTextColors).toEqual(['#fff']);
expect(tooltip.labelColors).toEqual([{
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}]);
expect(tooltip.x).toBeCloseToPixel(267);
expect(tooltip.y).toBeCloseToPixel(308);
});
it('Should display information from user callbacks', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'index',
callbacks: {
beforeTitle: function() {
return 'beforeTitle';
},
title: function() {
return 'title';
},
afterTitle: function() {
return 'afterTitle';
},
beforeBody: function() {
return 'beforeBody';
},
beforeLabel: function() {
return 'beforeLabel';
},
label: function() {
return 'label';
},
afterLabel: function() {
return 'afterLabel';
},
afterBody: function() {
return 'afterBody';
},
beforeFooter: function() {
return 'beforeFooter';
},
footer: function() {
return 'footer';
},
afterFooter: function() {
return 'afterFooter';
},
labelTextColor: function() {
return 'labelTextColor';
},
labelPointStyle: function() {
return {
pointStyle: 'labelPointStyle',
rotation: 42
};
}
}
}
}
}
});
// Trigger an event over top of the
var meta = chart.getDatasetMeta(0);
var point = meta.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
var defaults = Chart.defaults;
expect(tooltip.options.padding).toEqual(6);
expect(tooltip.xAlign).toEqual('left');
expect(tooltip.yAlign).toEqual('center');
expect(tooltip.options.bodyFont).toEqual(jasmine.objectContaining({
family: defaults.font.family,
style: defaults.font.style,
size: defaults.font.size,
}));
expect(tooltip.options).toEqualOptions({
bodyAlign: 'left',
bodySpacing: 2,
});
expect(tooltip.options.titleFont).toEqual(jasmine.objectContaining({
family: defaults.font.family,
weight: 'bold',
size: defaults.font.size,
}));
expect(tooltip.options).toEqualOptions({
titleSpacing: 2,
titleMarginBottom: 6,
});
expect(tooltip.options.footerFont).toEqual(jasmine.objectContaining({
family: defaults.font.family,
weight: 'bold',
size: defaults.font.size,
}));
expect(tooltip.options).toEqualOptions({
footerAlign: 'left',
footerSpacing: 2,
footerMarginTop: 6,
});
expect(tooltip.options).toEqualOptions({
// Appearance
caretSize: 5,
caretPadding: 2,
cornerRadius: 6,
backgroundColor: 'rgba(0,0,0,0.8)',
multiKeyBackground: '#fff',
});
expect(tooltip).toEqual(jasmine.objectContaining({
opacity: 1,
// Text
title: ['beforeTitle', 'title', 'afterTitle'],
beforeBody: ['beforeBody'],
body: [{
before: ['beforeLabel'],
lines: ['label'],
after: ['afterLabel']
}, {
before: ['beforeLabel'],
lines: ['label'],
after: ['afterLabel']
}],
afterBody: ['afterBody'],
footer: ['beforeFooter', 'footer', 'afterFooter'],
labelTextColors: ['labelTextColor', 'labelTextColor'],
labelColors: [{
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}, {
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}],
labelPointStyles: [{
pointStyle: 'labelPointStyle',
rotation: 42
}, {
pointStyle: 'labelPointStyle',
rotation: 42
}]
}));
expect(tooltip.x).toBeCloseToPixel(267);
expect(tooltip.y).toBeCloseToPixel(58);
});
it('Should provide context object to user callbacks', async function() {
const chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [{x: 1, y: 10}, {x: 2, y: 20}, {x: 3, y: 30}]
}]
},
options: {
scales: {
x: {
type: 'linear'
}
},
plugins: {
tooltip: {
mode: 'index',
callbacks: {
beforeLabel: function(ctx) {
return ctx.parsed.x + ',' + ctx.parsed.y;
}
}
}
}
}
});
// Trigger an event over top of the
const meta = chart.getDatasetMeta(0);
const point = meta.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(chart.tooltip.body[0].before).toEqual(['2,20']);
});
it('Should allow sorting items', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'index',
itemSort: function(a, b) {
return a.datasetIndex > b.datasetIndex ? -1 : 1;
}
}
}
}
});
// Trigger an event over top of the
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point0);
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
var defaults = Chart.defaults;
expect(tooltip).toEqual(jasmine.objectContaining({
// Positioning
xAlign: 'left',
yAlign: 'center',
// Text
title: ['Point 2'],
beforeBody: [],
body: [{
before: [],
lines: ['Dataset 2: 40'],
after: []
}, {
before: [],
lines: ['Dataset 1: 20'],
after: []
}],
afterBody: [],
footer: [],
labelColors: [{
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}, {
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}]
}));
expect(tooltip.x).toBeCloseToPixel(267);
expect(tooltip.y).toBeCloseToPixel(150);
});
it('Should allow reversing items', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'index',
reverse: true
}
}
}
});
// Trigger an event over top of the
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point0);
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
var defaults = Chart.defaults;
expect(tooltip).toEqual(jasmine.objectContaining({
// Positioning
xAlign: 'left',
yAlign: 'center',
// Text
title: ['Point 2'],
beforeBody: [],
body: [{
before: [],
lines: ['Dataset 2: 40'],
after: []
}, {
before: [],
lines: ['Dataset 1: 20'],
after: []
}],
afterBody: [],
footer: [],
labelColors: [{
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}, {
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}]
}));
expect(tooltip.x).toBeCloseToPixel(267);
expect(tooltip.y).toBeCloseToPixel(150);
});
it('Should follow dataset order', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)',
order: 10
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)',
order: 5
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'index'
}
}
}
});
// Trigger an event over top of the
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point0);
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
var defaults = Chart.defaults;
expect(tooltip).toEqual(jasmine.objectContaining({
// Positioning
xAlign: 'left',
yAlign: 'center',
// Text
title: ['Point 2'],
beforeBody: [],
body: [{
before: [],
lines: ['Dataset 2: 40'],
after: []
}, {
before: [],
lines: ['Dataset 1: 20'],
after: []
}],
afterBody: [],
footer: [],
labelColors: [{
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}, {
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}]
}));
expect(tooltip.x).toBeCloseToPixel(267);
expect(tooltip.y).toBeCloseToPixel(150);
});
it('should filter items from the tooltip using the callback', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)',
tooltipHidden: true
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'index',
filter: function(tooltipItem, index, tooltipItems, data) {
// For testing purposes remove the first dataset that has a tooltipHidden property
return !data.datasets[tooltipItem.datasetIndex].tooltipHidden;
}
}
}
}
});
// Trigger an event over top of the
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point0);
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
var defaults = Chart.defaults;
expect(tooltip).toEqual(jasmine.objectContaining({
// Positioning
xAlign: 'left',
yAlign: 'center',
// Text
title: ['Point 2'],
beforeBody: [],
body: [{
before: [],
lines: ['Dataset 2: 40'],
after: []
}],
afterBody: [],
footer: [],
labelColors: [{
borderColor: defaults.borderColor,
backgroundColor: defaults.backgroundColor,
borderWidth: 1,
borderDash: undefined,
borderDashOffset: undefined,
borderRadius: 0,
}]
}));
});
it('should set the caretPadding based on a config setting', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)',
tooltipHidden: true
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
caretPadding: 10
}
}
}
});
// Trigger an event over top of the
var meta0 = chart.getDatasetMeta(0);
var point0 = meta0.data[1];
await jasmine.triggerMouseEvent(chart, 'mousemove', point0);
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
expect(tooltip.options).toEqualOptions({
// Positioning
caretPadding: 10,
});
});
['line', 'bar'].forEach(function(type) {
it('Should have dataPoints in a ' + type + ' chart', async function() {
var chart = window.acquireChart({
type: type,
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'nearest',
intersect: true
}
}
}
});
// Trigger an event over top of the element
var pointIndex = 1;
var datasetIndex = 0;
var point = chart.getDatasetMeta(datasetIndex).data[pointIndex];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
// Check and see if tooltip was displayed
var tooltip = chart.tooltip;
expect(tooltip instanceof Object).toBe(true);
expect(tooltip.dataPoints instanceof Array).toBe(true);
expect(tooltip.dataPoints.length).toBe(1);
var tooltipItem = tooltip.dataPoints[0];
expect(tooltipItem.dataIndex).toBe(pointIndex);
expect(tooltipItem.datasetIndex).toBe(datasetIndex);
expect(typeof tooltipItem.label).toBe('string');
expect(tooltipItem.label).toBe(chart.data.labels[pointIndex]);
expect(typeof tooltipItem.formattedValue).toBe('string');
expect(tooltipItem.formattedValue).toBe('' + chart.data.datasets[datasetIndex].data[pointIndex]);
});
});
it('Should not update if active element has not changed', async function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'nearest',
intersect: true,
callbacks: {
title: function() {
return 'registering callback...';
}
}
}
}
}
});
// Trigger an event over top of the
var meta = chart.getDatasetMeta(0);
var firstPoint = meta.data[1];
var tooltip = chart.tooltip;
spyOn(tooltip, 'update').and.callThrough();
// First dispatch change event, should update tooltip
await jasmine.triggerMouseEvent(chart, 'mousemove', firstPoint);
expect(tooltip.update).toHaveBeenCalledWith(true, undefined);
// Reset calls
tooltip.update.calls.reset();
// Second dispatch change event (same event), should not update tooltip
await jasmine.triggerMouseEvent(chart, 'mousemove', firstPoint);
expect(tooltip.update).not.toHaveBeenCalled();
});
it('Should update if active elements are the same, but the position has changed', async function() {
const chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
},
plugins: {
tooltip: {
mode: 'nearest',
position: 'nearest',
intersect: true,
callbacks: {
title: function() {
return 'registering callback...';
}
}
}
}
}
});
// Trigger an event over top of the
const meta = chart.getDatasetMeta(0);
const firstPoint = meta.data[1];
const meta2 = chart.getDatasetMeta(1);
const secondPoint = meta2.data[1];
const tooltip = chart.tooltip;
spyOn(tooltip, 'update');
// First dispatch change event, should update tooltip
await jasmine.triggerMouseEvent(chart, 'mousemove', firstPoint);
expect(tooltip.update).toHaveBeenCalledWith(true, undefined);
// Reset calls
tooltip.update.calls.reset();
// Second dispatch change event (same event), should update tooltip
// because position mode is 'nearest'
await jasmine.triggerMouseEvent(chart, 'mousemove', secondPoint);
expect(tooltip.update).toHaveBeenCalledWith(true, undefined);
});
describe('positioners', function() {
it('Should call custom positioner with correct parameters and scope', async function() {
tooltipPlugin.positioners.test = function() {
return {x: 0, y: 0};
};
spyOn(tooltipPlugin.positioners, 'test').and.callThrough();
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)'
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
plugins: {
tooltip: {
mode: 'nearest',
position: 'test'
}
}
}
});
// Trigger an event over top of the
var pointIndex = 1;
var datasetIndex = 0;
var meta = chart.getDatasetMeta(datasetIndex);
var point = meta.data[pointIndex];
var fn = tooltipPlugin.positioners.test;
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(fn.calls.count()).toBe(2);
expect(fn.calls.first().args[0] instanceof Array).toBe(true);
expect(Object.prototype.hasOwnProperty.call(fn.calls.first().args[1], 'x')).toBe(true);
expect(Object.prototype.hasOwnProperty.call(fn.calls.first().args[1], 'y')).toBe(true);
expect(fn.calls.first().object instanceof Tooltip).toBe(true);
});
it('Should ignore same x position when calculating average position with index interaction on stacked bar', async function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
label: 'Dataset 1',
data: [10, 20, 30],
pointHoverBorderColor: 'rgb(255, 0, 0)',
pointHoverBackgroundColor: 'rgb(0, 255, 0)',
stack: 'stack1',
}, {
label: 'Dataset 2',
data: [40, 40, 40],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)',
stack: 'stack1',
}, {
label: 'Dataset 3',
data: [90, 100, 110],
pointHoverBorderColor: 'rgb(0, 0, 255)',
pointHoverBackgroundColor: 'rgb(0, 255, 255)'
}],
labels: ['Point 1', 'Point 2', 'Point 3']
},
options: {
interaction: {
mode: 'index'
},
plugins: {
position: 'average',
},
}
});
// Trigger an event over top of the
var pointIndex = 1;
var datasetIndex = 0;
var meta = chart.getDatasetMeta(datasetIndex);
var point = meta.data[pointIndex];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
var tooltipModel = chart.tooltip;
const activeElements = tooltipModel.getActiveElements();
const xPositionArray = activeElements.map((element) => element.element.x);
const xPositionArrayAverage = xPositionArray.reduce((a, b) => a + b) / xPositionArray.length;
const xPositionSet = new Set(xPositionArray);
const xPositionSetAverage = [...xPositionSet].reduce((a, b) => a + b) / xPositionSet.size;
expect(xPositionArray.length).toBe(3);
expect(xPositionSet.size).toBe(2);
expect(tooltipModel.caretX).not.toBe(xPositionArrayAverage);
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | true |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/scale.category.tests.js | test/specs/scale.category.tests.js | function getLabels(scale) {
return scale.ticks.map(t => t.label);
}
describe('Category scale tests', function() {
describe('auto', jasmine.fixture.specs('scale.category'));
it('Should register the constructor with the registry', function() {
var Constructor = Chart.registry.getScale('category');
expect(Constructor).not.toBe(undefined);
expect(typeof Constructor).toBe('function');
});
it('Should have the correct default config', function() {
var defaultConfig = Chart.defaults.scales.category;
expect(defaultConfig).toEqual({
ticks: {
callback: Chart.registry.getScale('category').defaults.ticks.callback
}
});
});
it('Should generate ticks from the data xLabels', function() {
var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'];
var chart = window.acquireChart({
type: 'line',
data: {
xLabels: labels,
datasets: [{
data: [10, 5, 0, 25, 78]
}]
},
options: {
scales: {
x: {
type: 'category',
}
}
}
});
var scale = chart.scales.x;
expect(getLabels(scale)).toEqual(labels);
});
it('Should generate ticks from the data yLabels', function() {
var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'];
var chart = window.acquireChart({
type: 'line',
data: {
yLabels: labels,
datasets: [{
data: [10, 5, 0, 25, 78]
}]
},
options: {
scales: {
y: {
type: 'category'
}
}
}
});
var scale = chart.scales.y;
expect(getLabels(scale)).toEqual(labels);
});
it('Should generate ticks from the axis labels', function() {
var labels = ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'];
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [10, 5, 0, 25, 78]
}]
},
options: {
scales: {
x: {
type: 'category',
labels: labels
}
}
}
});
var scale = chart.scales.x;
expect(getLabels(scale)).toEqual(labels);
});
it('Should generate missing labels', function() {
var labels = ['a', 'b', 'c', 'd'];
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: {a: 1, b: 3, c: -1, d: 10}
}]
},
options: {
scales: {
x: {
type: 'category',
labels: ['a']
}
}
}
});
var scale = chart.scales.x;
expect(getLabels(scale)).toEqual(labels);
});
it('should parse only to a valid index', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [10, 5, 0, 25, 78]
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
var scale = chart.scales.x;
expect(scale.parse(-10)).toEqual(0);
expect(scale.parse(-0.1)).toEqual(0);
expect(scale.parse(4.1)).toEqual(4);
expect(scale.parse(5)).toEqual(4);
expect(scale.parse(1)).toEqual(1);
expect(scale.parse(1.4)).toEqual(1);
expect(scale.parse(1.5)).toEqual(2);
expect(scale.parse('tick2')).toEqual(1);
});
it('should get the correct label for the index', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [10, 5, 0, 25, 78]
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5']
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
var scale = chart.scales.x;
expect(scale.getLabelForValue(1)).toBe('tick2');
});
it('Should get the correct pixel for a value when horizontal', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [10, 5, 0, 25, 78]
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick_last']
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
var xScale = chart.scales.x;
expect(xScale.getPixelForValue(0)).toBeCloseToPixel(23 + 6); // plus lineHeight
expect(xScale.getValueForPixel(23)).toBe(0);
expect(xScale.getPixelForValue(4)).toBeCloseToPixel(487);
expect(xScale.getValueForPixel(487)).toBe(4);
xScale.options.offset = true;
chart.update();
expect(xScale.getPixelForValue(0)).toBeCloseToPixel(71 + 6); // plus lineHeight
expect(xScale.getValueForPixel(69)).toBe(0);
expect(xScale.getPixelForValue(4)).toBeCloseToPixel(461);
expect(xScale.getValueForPixel(417)).toBe(4);
});
it('Should get the correct pixel for a value when there are repeated labels', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [10, 5, 0, 25, 78]
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick_last']
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
var xScale = chart.scales.x;
expect(xScale.getPixelForValue('tick1')).toBeCloseToPixel(23 + 6); // plus lineHeight
});
it('Should get the correct pixel for a value when horizontal and zoomed', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [10, 5, 0, 25, 78]
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick_last']
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom',
min: 'tick2',
max: 'tick4'
},
y: {
type: 'linear'
}
}
}
});
var xScale = chart.scales.x;
expect(xScale.getPixelForValue(1)).toBeCloseToPixel(23 + 6); // plus lineHeight
expect(xScale.getPixelForValue(3)).toBeCloseToPixel(496);
xScale.options.offset = true;
chart.update();
expect(xScale.getPixelForValue(1)).toBeCloseToPixel(103 + 6); // plus lineHeight
expect(xScale.getPixelForValue(3)).toBeCloseToPixel(429);
});
it('should get the correct pixel for a value when vertical', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: ['3', '5', '1', '4', '2']
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'],
yLabels: ['1', '2', '3', '4', '5']
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom',
},
y: {
type: 'category',
position: 'left'
}
}
}
});
var yScale = chart.scales.y;
expect(yScale.getPixelForValue(0)).toBeCloseToPixel(32);
expect(yScale.getValueForPixel(257)).toBe(2);
expect(yScale.getPixelForValue(4)).toBeCloseToPixel(484);
expect(yScale.getValueForPixel(144)).toBe(1);
yScale.options.offset = true;
chart.update();
expect(yScale.getPixelForValue(0)).toBeCloseToPixel(77);
expect(yScale.getValueForPixel(256)).toBe(2);
expect(yScale.getPixelForValue(4)).toBeCloseToPixel(438);
expect(yScale.getValueForPixel(167)).toBe(1);
});
it('should get the correct pixel for a value when vertical and zoomed', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: ['3', '5', '1', '4', '2']
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5'],
yLabels: ['1', '2', '3', '4', '5']
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom',
},
y: {
type: 'category',
position: 'left',
min: '2',
max: '4'
}
}
}
});
var yScale = chart.scales.y;
expect(yScale.getPixelForValue(1)).toBeCloseToPixel(32);
expect(yScale.getPixelForValue(3)).toBeCloseToPixel(482);
yScale.options.offset = true;
chart.update();
expect(yScale.getPixelForValue(1)).toBeCloseToPixel(107);
expect(yScale.getPixelForValue(3)).toBeCloseToPixel(407);
});
it('Should get the correct pixel for an object value when horizontal', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [
{x: 0, y: 10},
{x: 1, y: 5},
{x: 2, y: 0},
{x: 3, y: 25},
{x: 0, y: 78}
]
}],
labels: [0, 1, 2, 3]
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
var xScale = chart.scales.x;
expect(xScale.getPixelForValue(0)).toBeCloseToPixel(29);
expect(xScale.getPixelForValue(3)).toBeCloseToPixel(506);
expect(xScale.getPixelForValue(4)).toBeCloseToPixel(664);
});
it('Should get the correct pixel for an object value when vertical', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [
{x: 0, y: 2},
{x: 1, y: 4},
{x: 2, y: 0},
{x: 3, y: 3},
{x: 0, y: 1}
]
}],
labels: [0, 1, 2, 3],
yLabels: [0, 1, 2, 3, 4]
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom'
},
y: {
type: 'category',
position: 'left'
}
}
}
});
var yScale = chart.scales.y;
expect(yScale.getPixelForValue(0)).toBeCloseToPixel(32);
expect(yScale.getPixelForValue(4)).toBeCloseToPixel(483);
});
it('Should get the correct pixel for an object value in a bar chart', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
xAxisID: 'x',
yAxisID: 'y',
data: [
{x: 0, y: 10},
{x: 1, y: 5},
{x: 2, y: 0},
{x: 3, y: 25},
{x: 0, y: 78}
]
}],
labels: [0, 1, 2, 3]
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom'
},
y: {
type: 'linear'
}
}
}
});
var xScale = chart.scales.x;
expect(xScale.getPixelForValue(0)).toBeCloseToPixel(89);
expect(xScale.getPixelForValue(3)).toBeCloseToPixel(451);
expect(xScale.getPixelForValue(4)).toBeCloseToPixel(572);
});
it('Should get the correct pixel for an object value in a horizontal bar chart', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
data: [
{x: 10, y: 0},
{x: 5, y: 1},
{x: 0, y: 2},
{x: 25, y: 3},
{x: 78, y: 0}
]
}],
labels: [0, 1, 2, 3]
},
options: {
indexAxis: 'y',
scales: {
x: {
type: 'linear',
position: 'bottom'
},
y: {
type: 'category'
}
}
}
});
var yScale = chart.scales.y;
expect(yScale.getPixelForValue(0)).toBeCloseToPixel(88);
expect(yScale.getPixelForValue(3)).toBeCloseToPixel(426);
expect(yScale.getPixelForValue(4)).toBeCloseToPixel(538);
});
it('Should be consistent on pixels and values with autoSkipped ticks', function() {
var labels = [];
for (let i = 0; i < 50; i++) {
labels.push('very long label ' + i);
}
var chart = window.acquireChart({
type: 'bar',
data: {
labels,
datasets: [{
data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}]
}
});
var scale = chart.scales.x;
expect(scale.ticks.length).toBeLessThan(50);
let x = 0;
for (let i = 0; i < 50; i++) {
var x2 = scale.getPixelForValue(labels[i]);
var x3 = scale.getPixelForValue(i);
expect(x2).toEqual(x3);
expect(x2).toBeGreaterThan(x);
expect(scale.getValueForPixel(x2)).toBe(i);
x = x2;
}
});
it('Should bound to ticks/data', function() {
var chart = window.acquireChart({
type: 'line',
data: {
labels: ['a', 'b', 'c', 'd'],
datasets: [{
data: {b: 1, c: 99}
}]
},
options: {
scales: {
x: {
type: 'category',
bounds: 'data'
}
}
}
});
expect(chart.scales.x.min).toEqual(1);
expect(chart.scales.x.max).toEqual(2);
chart.options.scales.x.bounds = 'ticks';
chart.update();
expect(chart.scales.x.min).toEqual(0);
expect(chart.scales.x.max).toEqual(3);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/element.line.tests.js | test/specs/element.line.tests.js | // Tests for the line element
describe('Chart.elements.LineElement', function() {
describe('auto', jasmine.fixture.specs('element.line'));
it('should be constructed', function() {
var line = new Chart.elements.LineElement({
points: [1, 2, 3, 4]
});
expect(line).not.toBe(undefined);
expect(line.points).toEqual([1, 2, 3, 4]);
});
it('should not cache path when animations are enabled', function(done) {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: [0, -1, 0],
label: 'dataset1',
}],
labels: ['label1', 'label2', 'label3']
},
options: {
animation: {
duration: 50,
onComplete: () => {
expect(chart.getDatasetMeta(0).dataset._path).toBeUndefined();
done();
}
}
}
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/global.namespace.tests.js | test/specs/global.namespace.tests.js | describe('Chart namespace', function() {
describe('Chart', function() {
it('should a function (constructor)', function() {
expect(Chart instanceof Function).toBeTruthy();
});
it('should define "core" properties', function() {
expect(Chart instanceof Function).toBeTruthy();
expect(Chart.Animation instanceof Object).toBeTruthy();
expect(Chart.Animations instanceof Object).toBeTruthy();
expect(Chart.defaults instanceof Object).toBeTruthy();
expect(Chart.Element instanceof Object).toBeTruthy();
expect(Chart.Interaction instanceof Object).toBeTruthy();
expect(Chart.layouts instanceof Object).toBeTruthy();
expect(Chart.platforms.BasePlatform instanceof Function).toBeTruthy();
expect(Chart.platforms.BasicPlatform instanceof Function).toBeTruthy();
expect(Chart.platforms.DomPlatform instanceof Function).toBeTruthy();
expect(Chart.registry instanceof Object).toBeTruthy();
expect(Chart.Scale instanceof Object).toBeTruthy();
expect(Chart.Ticks instanceof Object).toBeTruthy();
});
});
describe('Chart.elements', function() {
it('should contains "elements" classes', function() {
expect(Chart.elements.ArcElement instanceof Function).toBeTruthy();
expect(Chart.elements.BarElement instanceof Function).toBeTruthy();
expect(Chart.elements.LineElement instanceof Function).toBeTruthy();
expect(Chart.elements.PointElement instanceof Function).toBeTruthy();
});
});
describe('Chart.helpers', function() {
it('should be an object', function() {
expect(Chart.helpers instanceof Object).toBeTruthy();
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/platform.dom.tests.js | test/specs/platform.dom.tests.js | const DomPlatform = Chart.platforms.DomPlatform;
describe('Platform.dom', function() {
describe('context acquisition', function() {
var canvasId = 'chartjs-canvas';
beforeEach(function() {
var canvas = document.createElement('canvas');
canvas.setAttribute('id', canvasId);
window.document.body.appendChild(canvas);
});
afterEach(function() {
document.getElementById(canvasId).remove();
});
it('should use the DomPlatform by default', function() {
var chart = acquireChart({type: 'line'});
expect(chart.platform).toBeInstanceOf(Chart.platforms.DomPlatform);
chart.destroy();
});
// see https://github.com/chartjs/Chart.js/issues/2807
it('should gracefully handle invalid item', function() {
var chart = new Chart('foobar');
expect(chart).not.toBeValidChart();
chart.destroy();
});
it('should accept a DOM element id', function() {
var canvas = document.getElementById(canvasId);
var chart = new Chart(canvasId);
expect(chart).toBeValidChart();
expect(chart.canvas).toBe(canvas);
expect(chart.ctx).toBe(canvas.getContext('2d'));
chart.destroy();
});
it('should accept a canvas element', function() {
var canvas = document.getElementById(canvasId);
var chart = new Chart(canvas);
expect(chart).toBeValidChart();
expect(chart.canvas).toBe(canvas);
expect(chart.ctx).toBe(canvas.getContext('2d'));
chart.destroy();
});
it('should accept a canvas context2D', function() {
var canvas = document.getElementById(canvasId);
var context = canvas.getContext('2d');
var chart = new Chart(context);
expect(chart).toBeValidChart();
expect(chart.canvas).toBe(canvas);
expect(chart.ctx).toBe(context);
chart.destroy();
});
it('should accept an array containing canvas', function() {
var canvas = document.getElementById(canvasId);
var chart = new Chart([canvas]);
expect(chart).toBeValidChart();
expect(chart.canvas).toBe(canvas);
expect(chart.ctx).toBe(canvas.getContext('2d'));
chart.destroy();
});
it('should accept a canvas from an iframe', function(done) {
var iframe = document.createElement('iframe');
iframe.onload = function() {
var doc = iframe.contentDocument;
doc.body.innerHTML += '<canvas id="chart"></canvas>';
var canvas = doc.getElementById('chart');
var chart = new Chart(canvas);
expect(chart).toBeValidChart();
expect(chart.canvas).toBe(canvas);
expect(chart.ctx).toBe(canvas.getContext('2d'));
chart.destroy();
canvas.remove();
iframe.remove();
done();
};
document.body.appendChild(iframe);
});
});
describe('config.options.aspectRatio', function() {
it('should use default "global" aspect ratio for render and display sizes', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 620px'
}
});
expect(chart).toBeChartOfSize({
dw: 620, dh: 310,
rw: 620, rh: 310,
});
});
it('should use default "chart" aspect ratio for render and display sizes', function() {
var ratio = Chart.overrides.doughnut.aspectRatio;
Chart.overrides.doughnut.aspectRatio = 1;
var chart = acquireChart({
type: 'doughnut',
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 425px'
}
});
Chart.overrides.doughnut.aspectRatio = ratio;
expect(chart).toBeChartOfSize({
dw: 425, dh: 425,
rw: 425, rh: 425,
});
});
it('should use "user" aspect ratio for render and display sizes', function() {
var chart = acquireChart({
options: {
responsive: false,
aspectRatio: 3
}
}, {
canvas: {
style: 'width: 405px'
}
});
expect(chart).toBeChartOfSize({
dw: 405, dh: 135,
rw: 405, rh: 135,
});
});
it('should not apply aspect ratio when height specified', function() {
var chart = acquireChart({
options: {
responsive: false,
aspectRatio: 3
}
}, {
canvas: {
style: 'width: 400px; height: 410px'
}
});
expect(chart).toBeChartOfSize({
dw: 400, dh: 410,
rw: 400, rh: 410,
});
});
});
describe('config.options.responsive: false', function() {
it('should use default canvas size for render and display sizes', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: ''
}
});
expect(chart).toBeChartOfSize({
dw: 300, dh: 150,
rw: 300, rh: 150,
});
});
it('should use canvas attributes for render and display sizes', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: '',
width: 305,
height: 245,
}
});
expect(chart).toBeChartOfSize({
dw: 305, dh: 245,
rw: 305, rh: 245,
});
});
it('should use canvas style for render and display sizes (if no attributes)', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 345px; height: 125px'
}
});
expect(chart).toBeChartOfSize({
dw: 345, dh: 125,
rw: 345, rh: 125,
});
});
it('should use attributes for the render size and style for the display size', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 345px; height: 125px;',
width: 165,
height: 85,
}
});
expect(chart).toBeChartOfSize({
dw: 345, dh: 125,
rw: 165, rh: 85,
});
});
// https://github.com/chartjs/Chart.js/issues/3860
it('should support decimal display width and/or height', function() {
var chart = acquireChart({
options: {
responsive: false
}
}, {
canvas: {
style: 'width: 345.42px; height: 125.42px;'
}
});
expect(chart).toBeChartOfSize({
dw: 345, dh: 125,
rw: 345, rh: 125,
});
});
});
describe('config.options.responsive: true (maintainAspectRatio: true)', function() {
it('should fit parent using aspect ratio to calculate size', function() {
var chart = acquireChart({
options: {
responsive: true,
maintainAspectRatio: true
}
}, {
canvas: {
style: 'width: 150px; height: 245px'
},
wrapper: {
style: 'width: 300px; height: 350px'
}
});
waitForResize(chart, () => {
expect(chart).toBeChartOfSize({
dw: 214, dh: 350,
rw: 214, rh: 350,
});
});
});
});
describe('controller.destroy', function() {
it('should reset context to default values', function() {
var wrapper = document.createElement('div');
var canvas = document.createElement('canvas');
wrapper.appendChild(canvas);
window.document.body.appendChild(wrapper);
var chart = new Chart(canvas, {});
var context = chart.ctx;
chart.destroy();
// https://www.w3.org/TR/2dcontext/#conformance-requirements
Chart.helpers.each({
fillStyle: '#000000',
font: '10px sans-serif',
lineJoin: 'miter',
lineCap: 'butt',
lineWidth: 1,
miterLimit: 10,
shadowBlur: 0,
shadowColor: 'rgba(0, 0, 0, 0)',
shadowOffsetX: 0,
shadowOffsetY: 0,
strokeStyle: '#000000',
textAlign: 'start',
textBaseline: 'alphabetic'
}, function(value, key) {
expect(context[key]).toBe(value);
});
wrapper.parentNode.removeChild(wrapper);
});
it('should restore canvas initial values', function(done) {
var wrapper = document.createElement('div');
var canvas = document.createElement('canvas');
canvas.setAttribute('width', 180);
canvas.setAttribute('style', 'width: 512px; height: 480px');
wrapper.setAttribute('style', 'width: 450px; height: 450px; position: relative');
wrapper.appendChild(canvas);
window.document.body.appendChild(wrapper);
var chart = new Chart(canvas.getContext('2d'), {
options: {
responsive: true,
maintainAspectRatio: false
}
});
waitForResize(chart, function() {
expect(chart).toBeChartOfSize({
dw: 475, dh: 450,
rw: 475, rh: 450,
});
chart.destroy();
expect(canvas.getAttribute('width')).toBe('180');
expect(canvas.getAttribute('height')).toBe(null);
expect(canvas.style.width).toBe('512px');
expect(canvas.style.height).toBe('480px');
expect(canvas.style.display).toBe('');
wrapper.parentNode.removeChild(wrapper);
done();
});
wrapper.style.width = '475px';
});
});
describe('event handling', function() {
it('should notify plugins about events', async function() {
var notifiedEvent;
var plugin = {
afterEvent: function(chart, args) {
notifiedEvent = args.event;
}
};
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
responsive: true
},
plugins: [plugin]
});
await jasmine.triggerMouseEvent(chart, 'click', {
x: chart.width / 2,
y: chart.height / 2
});
// Check that notifiedEvent is correct
expect(notifiedEvent).not.toBe(undefined);
// Is type correctly translated
expect(notifiedEvent.type).toBe('click');
// Relative Position
expect(notifiedEvent.x).toBeCloseToPixel(chart.width / 2);
expect(notifiedEvent.y).toBeCloseToPixel(chart.height / 2);
});
});
describe('isAttached', function() {
it('should detect detached when canvas is attached to DOM', function() {
var platform = new DomPlatform();
var canvas = document.createElement('canvas');
var div = document.createElement('div');
var anotherDiv = document.createElement('div');
expect(platform.isAttached(canvas)).toEqual(false);
div.appendChild(canvas);
expect(platform.isAttached(canvas)).toEqual(false);
anotherDiv.appendChild(div);
expect(platform.isAttached(canvas)).toEqual(false);
document.body.appendChild(anotherDiv);
expect(platform.isAttached(canvas)).toEqual(true);
anotherDiv.removeChild(div);
expect(platform.isAttached(canvas)).toEqual(false);
div.removeChild(canvas);
expect(platform.isAttached(canvas)).toEqual(false);
document.body.removeChild(anotherDiv);
expect(platform.isAttached(canvas)).toEqual(false);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.collection.tests.js | test/specs/helpers.collection.tests.js | const {_filterBetween, _lookup, _lookupByKey, _rlookupByKey} = Chart.helpers;
describe('helpers.collection', function() {
it('Should do binary search', function() {
const data = [0, 2, 6, 9];
expect(_lookup(data, 0)).toEqual({lo: 0, hi: 1});
expect(_lookup(data, 1)).toEqual({lo: 0, hi: 1});
expect(_lookup(data, 3)).toEqual({lo: 1, hi: 2});
expect(_lookup(data, 6)).toEqual({lo: 1, hi: 2});
expect(_lookup(data, 9)).toEqual({lo: 2, hi: 3});
});
it('Should do binary search by key', function() {
const data = [{x: 0}, {x: 2}, {x: 6}, {x: 9}];
expect(_lookupByKey(data, 'x', 0)).toEqual({lo: 0, hi: 1});
expect(_lookupByKey(data, 'x', 1)).toEqual({lo: 0, hi: 1});
expect(_lookupByKey(data, 'x', 3)).toEqual({lo: 1, hi: 2});
expect(_lookupByKey(data, 'x', 6)).toEqual({lo: 1, hi: 2});
expect(_lookupByKey(data, 'x', 9)).toEqual({lo: 2, hi: 3});
});
it('Should do binary search by key with last', () => {
expect(_lookupByKey([{x: 0}, {x: 2}, {x: 6}, {x: 9}], 'x', 25, true)).toEqual({lo: 2, hi: 3});
expect(_lookupByKey([{x: 0}, {x: 2}, {x: 9}, {x: 9}], 'x', 25, true)).toEqual({lo: 2, hi: 3});
expect(_lookupByKey([{x: 0}, {x: 2}, {x: 9}, {x: 9}, {x: 22}], 'x', 25, true)).toEqual({lo: 3, hi: 4});
expect(_lookupByKey([{x: 0}, {x: 2}, {x: 25}, {x: 28}], 'x', 25, true)).toEqual({lo: 1, hi: 2});
expect(_lookupByKey([{x: 0}, {x: 2}, {x: 25}, {x: 25}], 'x', 25, true)).toEqual({lo: 2, hi: 3});
expect(_lookupByKey([{x: 0}, {x: 2}, {x: 25}, {x: 25}, {x: 28}], 'x', 25, true)).toEqual({lo: 2, hi: 3});
expect(_lookupByKey([{x: 0}, {x: 2}, {x: 25}, {x: 25}, {x: 25}, {x: 28}, {x: 29}], 'x', 25, true)).toEqual({lo: 3, hi: 4});
});
it('Should do reverse binary search by key', function() {
const data = [{x: 10}, {x: 7}, {x: 3}, {x: 0}];
expect(_rlookupByKey(data, 'x', 0)).toEqual({lo: 2, hi: 3});
expect(_rlookupByKey(data, 'x', 3)).toEqual({lo: 2, hi: 3});
expect(_rlookupByKey(data, 'x', 5)).toEqual({lo: 1, hi: 2});
expect(_rlookupByKey(data, 'x', 8)).toEqual({lo: 0, hi: 1});
expect(_rlookupByKey(data, 'x', 10)).toEqual({lo: 0, hi: 1});
});
it('Should filter a sorted array', function() {
expect(_filterBetween([1, 2, 3, 4, 5, 6, 7, 8, 9], 5, 8)).toEqual([5, 6, 7, 8]);
expect(_filterBetween([1], 1, 1)).toEqual([1]);
expect(_filterBetween([1583049600000], 1584816327553, 1585680327553)).toEqual([]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.core.tests.js | test/specs/helpers.core.tests.js | 'use strict';
describe('Chart.helpers.core', function() {
var helpers = Chart.helpers;
describe('noop', function() {
it('should be callable', function() {
expect(helpers.noop).toBeDefined();
expect(typeof helpers.noop).toBe('function');
expect(typeof helpers.noop.call).toBe('function');
});
it('should returns "undefined"', function() {
expect(helpers.noop(42)).not.toBeDefined();
expect(helpers.noop.call(this, 42)).not.toBeDefined();
});
});
describe('isArray', function() {
it('should return true if value is an array', function() {
expect(helpers.isArray([])).toBeTruthy();
expect(helpers.isArray([42])).toBeTruthy();
expect(helpers.isArray(new Array())).toBeTruthy();
expect(helpers.isArray(Array.prototype)).toBeTruthy();
expect(helpers.isArray(new Int8Array(2))).toBeTruthy();
expect(helpers.isArray(new Uint8Array())).toBeTruthy();
expect(helpers.isArray(new Uint8ClampedArray([128, 244]))).toBeTruthy();
expect(helpers.isArray(new Int16Array())).toBeTruthy();
expect(helpers.isArray(new Uint16Array())).toBeTruthy();
expect(helpers.isArray(new Int32Array())).toBeTruthy();
expect(helpers.isArray(new Uint32Array())).toBeTruthy();
expect(helpers.isArray(new Float32Array([1.2]))).toBeTruthy();
expect(helpers.isArray(new Float64Array([]))).toBeTruthy();
});
it('should return false if value is not an array', function() {
expect(helpers.isArray()).toBeFalsy();
expect(helpers.isArray({})).toBeFalsy();
expect(helpers.isArray(undefined)).toBeFalsy();
expect(helpers.isArray(null)).toBeFalsy();
expect(helpers.isArray(true)).toBeFalsy();
expect(helpers.isArray(false)).toBeFalsy();
expect(helpers.isArray(42)).toBeFalsy();
expect(helpers.isArray('Array')).toBeFalsy();
expect(helpers.isArray({__proto__: Array.prototype})).toBeFalsy();
});
});
describe('isObject', function() {
it('should return true if value is an object', function() {
expect(helpers.isObject({})).toBeTruthy();
expect(helpers.isObject({a: 42})).toBeTruthy();
expect(helpers.isObject(new Object())).toBeTruthy();
});
it('should return false if value is not an object', function() {
expect(helpers.isObject()).toBeFalsy();
expect(helpers.isObject(undefined)).toBeFalsy();
expect(helpers.isObject(null)).toBeFalsy();
expect(helpers.isObject(true)).toBeFalsy();
expect(helpers.isObject(false)).toBeFalsy();
expect(helpers.isObject(42)).toBeFalsy();
expect(helpers.isObject('Object')).toBeFalsy();
expect(helpers.isObject([])).toBeFalsy();
expect(helpers.isObject([42])).toBeFalsy();
expect(helpers.isObject(new Array())).toBeFalsy();
expect(helpers.isObject(new Date())).toBeFalsy();
});
});
describe('isFinite', function() {
it('should return true if value is a finite number', function() {
expect(helpers.isFinite(0)).toBeTruthy();
// eslint-disable-next-line no-new-wrappers
expect(helpers.isFinite(new Number(10))).toBeTruthy();
});
it('should return false if the value is infinite', function() {
expect(helpers.isFinite(Number.POSITIVE_INFINITY)).toBeFalsy();
expect(helpers.isFinite(Number.NEGATIVE_INFINITY)).toBeFalsy();
});
it('should return false if the value is not a number', function() {
expect(helpers.isFinite('a')).toBeFalsy();
expect(helpers.isFinite({})).toBeFalsy();
});
});
describe('isNullOrUndef', function() {
it('should return true if value is null/undefined', function() {
expect(helpers.isNullOrUndef(null)).toBeTruthy();
expect(helpers.isNullOrUndef(undefined)).toBeTruthy();
});
it('should return false if value is not null/undefined', function() {
expect(helpers.isNullOrUndef(true)).toBeFalsy();
expect(helpers.isNullOrUndef(false)).toBeFalsy();
expect(helpers.isNullOrUndef('')).toBeFalsy();
expect(helpers.isNullOrUndef('String')).toBeFalsy();
expect(helpers.isNullOrUndef(0)).toBeFalsy();
expect(helpers.isNullOrUndef([])).toBeFalsy();
expect(helpers.isNullOrUndef({})).toBeFalsy();
expect(helpers.isNullOrUndef([42])).toBeFalsy();
expect(helpers.isNullOrUndef(new Date())).toBeFalsy();
});
});
describe('valueOrDefault', function() {
it('should return value if defined', function() {
var object = {};
var array = [];
expect(helpers.valueOrDefault(null, 42)).toBe(null);
expect(helpers.valueOrDefault(false, 42)).toBe(false);
expect(helpers.valueOrDefault(object, 42)).toBe(object);
expect(helpers.valueOrDefault(array, 42)).toBe(array);
expect(helpers.valueOrDefault('', 42)).toBe('');
expect(helpers.valueOrDefault(0, 42)).toBe(0);
});
it('should return default if undefined', function() {
expect(helpers.valueOrDefault(undefined, 42)).toBe(42);
expect(helpers.valueOrDefault({}.foo, 42)).toBe(42);
});
});
describe('callback', function() {
it('should return undefined if fn is not a function', function() {
expect(helpers.callback()).not.toBeDefined();
expect(helpers.callback(null)).not.toBeDefined();
expect(helpers.callback(42)).not.toBeDefined();
expect(helpers.callback([])).not.toBeDefined();
expect(helpers.callback({})).not.toBeDefined();
});
it('should call fn with the given args', function() {
var spy = jasmine.createSpy('spy');
helpers.callback(spy);
helpers.callback(spy, []);
helpers.callback(spy, ['foo']);
helpers.callback(spy, [42, 'bar']);
expect(spy.calls.argsFor(0)).toEqual([]);
expect(spy.calls.argsFor(1)).toEqual([]);
expect(spy.calls.argsFor(2)).toEqual(['foo']);
expect(spy.calls.argsFor(3)).toEqual([42, 'bar']);
});
it('should call fn with the given scope', function() {
var spy = jasmine.createSpy('spy');
var scope = {};
helpers.callback(spy);
helpers.callback(spy, [], null);
helpers.callback(spy, [], undefined);
helpers.callback(spy, [], scope);
expect(spy.calls.all()[0].object).toBe(window);
expect(spy.calls.all()[1].object).toBe(window);
expect(spy.calls.all()[2].object).toBe(window);
expect(spy.calls.all()[3].object).toBe(scope);
});
it('should return the value returned by fn', function() {
expect(helpers.callback(helpers.noop, [41])).toBe(undefined);
expect(helpers.callback(function(i) {
return i + 1;
}, [41])).toBe(42);
});
});
describe('each', function() {
it('should iterate over an array forward if reverse === false', function() {
var scope = {};
var scopes = [];
var items = [];
var keys = [];
helpers.each(['foo', 'bar', 42], function(item, key) {
scopes.push(this);
items.push(item);
keys.push(key);
}, scope);
expect(scopes).toEqual([scope, scope, scope]);
expect(items).toEqual(['foo', 'bar', 42]);
expect(keys).toEqual([0, 1, 2]);
});
it('should iterate over an array backward if reverse === true', function() {
var scope = {};
var scopes = [];
var items = [];
var keys = [];
helpers.each(['foo', 'bar', 42], function(item, key) {
scopes.push(this);
items.push(item);
keys.push(key);
}, scope, true);
expect(scopes).toEqual([scope, scope, scope]);
expect(items).toEqual([42, 'bar', 'foo']);
expect(keys).toEqual([2, 1, 0]);
});
it('should iterate over object properties', function() {
var scope = {};
var scopes = [];
var items = [];
helpers.each({a: 'foo', b: 'bar', c: 42}, function(item, key) {
scopes.push(this);
items[key] = item;
}, scope);
expect(scopes).toEqual([scope, scope, scope]);
expect(items).toEqual(jasmine.objectContaining({a: 'foo', b: 'bar', c: 42}));
});
it('should not throw when called with a non iterable object', function() {
expect(function() {
helpers.each(undefined);
}).not.toThrow();
expect(function() {
helpers.each(null);
}).not.toThrow();
expect(function() {
helpers.each(42);
}).not.toThrow();
});
});
describe('_elementsEqual', function() {
it('should return true if arrays are the same', function() {
expect(helpers._elementsEqual(
[{datasetIndex: 0, index: 1}, {datasetIndex: 0, index: 2}],
[{datasetIndex: 0, index: 1}, {datasetIndex: 0, index: 2}])).toBeTruthy();
});
it('should return false if arrays are not the same', function() {
expect(helpers._elementsEqual([], [{datasetIndex: 0, index: 1}])).toBeFalsy();
expect(helpers._elementsEqual([{datasetIndex: 0, index: 2}], [{datasetIndex: 0, index: 1}])).toBeFalsy();
});
});
describe('clone', function() {
it('should clone primitive values', function() {
expect(helpers.clone()).toBe(undefined);
expect(helpers.clone(null)).toBe(null);
expect(helpers.clone(true)).toBe(true);
expect(helpers.clone(42)).toBe(42);
expect(helpers.clone('foo')).toBe('foo');
});
it('should perform a deep copy of arrays', function() {
var o0 = {a: 42};
var o1 = {s: 's'};
var a0 = ['bar'];
var a1 = [a0, o0, 2];
var f0 = function() {};
var input = [a1, o1, f0, 42, 'foo'];
var output = helpers.clone(input);
expect(output).toEqual(input);
expect(output).not.toBe(input);
expect(output[0]).not.toBe(a1);
expect(output[0][0]).not.toBe(a0);
expect(output[1]).not.toBe(o1);
});
it('should perform a deep copy of objects', function() {
var a0 = ['bar'];
var a1 = [1, 2, 3];
var o0 = {a: a1, i: 42};
var f0 = function() {};
var input = {o: o0, a: a0, f: f0, s: 'foo', i: 42};
var output = helpers.clone(input);
expect(output).toEqual(input);
expect(output).not.toBe(input);
expect(output.o).not.toBe(o0);
expect(output.o.a).not.toBe(a1);
expect(output.a).not.toBe(a0);
});
});
describe('merge', function() {
it('should not allow prototype pollution', function() {
var test = helpers.merge({}, JSON.parse('{"__proto__":{"polluted": true}}'));
expect(test.prototype).toBeUndefined();
expect(Object.prototype.polluted).toBeUndefined();
});
it('should update target and return it', function() {
var target = {a: 1};
var result = helpers.merge(target, {a: 2, b: 'foo'});
expect(target).toEqual({a: 2, b: 'foo'});
expect(target).toBe(result);
});
it('should return target if not an object', function() {
expect(helpers.merge(undefined, {a: 42})).toEqual(undefined);
expect(helpers.merge(null, {a: 42})).toEqual(null);
expect(helpers.merge('foo', {a: 42})).toEqual('foo');
expect(helpers.merge(['foo', 'bar'], {a: 42})).toEqual(['foo', 'bar']);
});
it('should ignore sources which are not objects', function() {
expect(helpers.merge({a: 42})).toEqual({a: 42});
expect(helpers.merge({a: 42}, null)).toEqual({a: 42});
expect(helpers.merge({a: 42}, 42)).toEqual({a: 42});
});
it('should recursively overwrite target with source properties', function() {
expect(helpers.merge({a: {b: 1}}, {a: {c: 2}})).toEqual({a: {b: 1, c: 2}});
expect(helpers.merge({a: {b: 1}}, {a: {b: 2}})).toEqual({a: {b: 2}});
expect(helpers.merge({a: [1, 2]}, {a: [3, 4]})).toEqual({a: [3, 4]});
expect(helpers.merge({a: 42}, {a: {b: 0}})).toEqual({a: {b: 0}});
expect(helpers.merge({a: 42}, {a: null})).toEqual({a: null});
expect(helpers.merge({a: 42}, {a: undefined})).toEqual({a: undefined});
});
it('should merge multiple sources in the correct order', function() {
var t0 = {a: {b: 1, c: [1, 2]}};
var s0 = {a: {d: 3}, e: {f: 4}};
var s1 = {a: {b: 5}};
var s2 = {a: {c: [6, 7]}, e: 'foo'};
expect(helpers.merge(t0, [s0, s1, s2])).toEqual({a: {b: 5, c: [6, 7], d: 3}, e: 'foo'});
});
it('should deep copy merged values from sources', function() {
var a0 = ['foo'];
var a1 = [1, 2, 3];
var o0 = {a: a1, i: 42};
var output = helpers.merge({}, {a: a0, o: o0});
expect(output).toEqual({a: a0, o: o0});
expect(output.a).not.toBe(a0);
expect(output.o).not.toBe(o0);
expect(output.o.a).not.toBe(a1);
});
});
describe('mergeIf', function() {
it('should not allow prototype pollution', function() {
var test = helpers.mergeIf({}, JSON.parse('{"__proto__":{"polluted": true}}'));
expect(test.prototype).toBeUndefined();
expect(Object.prototype.polluted).toBeUndefined();
});
it('should update target and return it', function() {
var target = {a: 1};
var result = helpers.mergeIf(target, {a: 2, b: 'foo'});
expect(target).toEqual({a: 1, b: 'foo'});
expect(target).toBe(result);
});
it('should return target if not an object', function() {
expect(helpers.mergeIf(undefined, {a: 42})).toEqual(undefined);
expect(helpers.mergeIf(null, {a: 42})).toEqual(null);
expect(helpers.mergeIf('foo', {a: 42})).toEqual('foo');
expect(helpers.mergeIf(['foo', 'bar'], {a: 42})).toEqual(['foo', 'bar']);
});
it('should ignore sources which are not objects', function() {
expect(helpers.mergeIf({a: 42})).toEqual({a: 42});
expect(helpers.mergeIf({a: 42}, null)).toEqual({a: 42});
expect(helpers.mergeIf({a: 42}, 42)).toEqual({a: 42});
});
it('should recursively copy source properties in target only if they do not exist in target', function() {
expect(helpers.mergeIf({a: {b: 1}}, {a: {c: 2}})).toEqual({a: {b: 1, c: 2}});
expect(helpers.mergeIf({a: {b: 1}}, {a: {b: 2}})).toEqual({a: {b: 1}});
expect(helpers.mergeIf({a: [1, 2]}, {a: [3, 4]})).toEqual({a: [1, 2]});
expect(helpers.mergeIf({a: 0}, {a: {b: 2}})).toEqual({a: 0});
expect(helpers.mergeIf({a: null}, {a: 42})).toEqual({a: null});
expect(helpers.mergeIf({a: undefined}, {a: 42})).toEqual({a: undefined});
});
it('should merge multiple sources in the correct order', function() {
var t0 = {a: {b: 1, c: [1, 2]}};
var s0 = {a: {d: 3}, e: {f: 4}};
var s1 = {a: {b: 5}};
var s2 = {a: {c: [6, 7]}, e: 'foo'};
expect(helpers.mergeIf(t0, [s0, s1, s2])).toEqual({a: {b: 1, c: [1, 2], d: 3}, e: {f: 4}});
});
it('should deep copy merged values from sources', function() {
var a0 = ['foo'];
var a1 = [1, 2, 3];
var o0 = {a: a1, i: 42};
var output = helpers.mergeIf({}, {a: a0, o: o0});
expect(output).toEqual({a: a0, o: o0});
expect(output.a).not.toBe(a0);
expect(output.o).not.toBe(o0);
expect(output.o.a).not.toBe(a1);
});
});
describe('resolveObjectKey', function() {
it('should resolve empty key to root object', function() {
const obj = {test: true};
expect(helpers.resolveObjectKey(obj, '')).toEqual(obj);
});
it('should resolve one level', function() {
const obj = {
bool: true,
str: 'test',
int: 42,
obj: {name: 'object'}
};
expect(helpers.resolveObjectKey(obj, 'bool')).toEqual(true);
expect(helpers.resolveObjectKey(obj, 'str')).toEqual('test');
expect(helpers.resolveObjectKey(obj, 'int')).toEqual(42);
expect(helpers.resolveObjectKey(obj, 'obj')).toEqual(obj.obj);
});
it('should resolve multiple levels', function() {
const obj = {
child: {
level: 1,
child: {
level: 2,
child: {
level: 3
}
}
}
};
expect(helpers.resolveObjectKey(obj, 'child.level')).toEqual(1);
expect(helpers.resolveObjectKey(obj, 'child.child.level')).toEqual(2);
expect(helpers.resolveObjectKey(obj, 'child.child.child.level')).toEqual(3);
});
it('should resolve circular reference', function() {
const root = {};
const child = {root};
child.child = child;
root.child = child;
expect(helpers.resolveObjectKey(root, 'child')).toEqual(child);
expect(helpers.resolveObjectKey(root, 'child.child.child.child.child.child')).toEqual(child);
expect(helpers.resolveObjectKey(root, 'child.child.root')).toEqual(root);
});
it('should break at empty key', function() {
const obj = {
child: {
level: 1,
child: {
level: 2,
child: {
level: 3
}
}
}
};
expect(helpers.resolveObjectKey(obj, 'child..level')).toEqual(obj.child);
expect(helpers.resolveObjectKey(obj, 'child.child.level...')).toEqual(2);
expect(helpers.resolveObjectKey(obj, '.')).toEqual(obj);
expect(helpers.resolveObjectKey(obj, '..')).toEqual(obj);
});
it('should resolve undefined', function() {
const obj = {
child: {
level: 1,
child: {
level: 2,
child: {
level: 3
}
}
}
};
expect(helpers.resolveObjectKey(obj, 'level')).toEqual(undefined);
expect(helpers.resolveObjectKey(obj, 'child.level.a')).toEqual(undefined);
});
it('should throw on invalid input', function() {
expect(() => helpers.resolveObjectKey(undefined, undefined)).toThrow();
expect(() => helpers.resolveObjectKey({}, null)).toThrow();
expect(() => helpers.resolveObjectKey({}, false)).toThrow();
expect(() => helpers.resolveObjectKey({}, true)).toThrow();
expect(() => helpers.resolveObjectKey({}, 1)).toThrow();
});
it('should allow escaping dot symbol', function() {
expect(helpers.resolveObjectKey({'test.dot': 10}, 'test\\.dot')).toEqual(10);
expect(helpers.resolveObjectKey({test: {dot: 10}}, 'test\\.dot')).toEqual(undefined);
});
it('should allow nested keys with a dot', function() {
expect(helpers.resolveObjectKey({
a: {
'bb.ccc': 'works',
bb: {
ccc: 'fails'
}
}
}, 'a.bb\\.ccc')).toEqual('works');
});
});
describe('_splitKey', function() {
it('should return array with one entry for string without a dot', function() {
expect(helpers._splitKey('')).toEqual(['']);
expect(helpers._splitKey('test')).toEqual(['test']);
const asciiWithoutDot = ' !"#$%&\'()*+,-/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
expect(helpers._splitKey(asciiWithoutDot)).toEqual([asciiWithoutDot]);
});
it('should split on dot', function() {
expect(helpers._splitKey('test1.test2')).toEqual(['test1', 'test2']);
expect(helpers._splitKey('a.b.c')).toEqual(['a', 'b', 'c']);
expect(helpers._splitKey('a.b.')).toEqual(['a', 'b', '']);
expect(helpers._splitKey('a..c')).toEqual(['a', '', 'c']);
});
it('should preserve escaped dot', function() {
expect(helpers._splitKey('test1\\.test2')).toEqual(['test1.test2']);
expect(helpers._splitKey('a\\.b.c')).toEqual(['a.b', 'c']);
expect(helpers._splitKey('a.b\\.c')).toEqual(['a', 'b.c']);
expect(helpers._splitKey('a.\\.c')).toEqual(['a', '.c']);
});
});
describe('setsEqual', function() {
it('should handle set comparison', function() {
var a = new Set([1]);
var b = new Set(['1']);
var c = new Set([1]);
expect(helpers.setsEqual(a, b)).toBeFalse();
expect(helpers.setsEqual(a, c)).toBeTrue();
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.defaults.tests.js | test/specs/core.defaults.tests.js | describe('Chart.defaults', function() {
describe('.set', function() {
it('Should set defaults directly to root when scope is not provided', function() {
expect(Chart.defaults.test).toBeUndefined();
Chart.defaults.set({test: true});
expect(Chart.defaults.test).toEqual(true);
delete Chart.defaults.test;
});
it('Should create scope when it does not exist', function() {
expect(Chart.defaults.test).toBeUndefined();
Chart.defaults.set('test', {value: true});
expect(Chart.defaults.test.value).toEqual(true);
delete Chart.defaults.test;
});
});
describe('.route', function() {
it('Should read the source, but not change it', function() {
expect(Chart.defaults.testscope).toBeUndefined();
Chart.defaults.set('testscope', {test: true});
Chart.defaults.route('testscope', 'test2', 'testscope', 'test');
expect(Chart.defaults.testscope.test).toEqual(true);
expect(Chart.defaults.testscope.test2).toEqual(true);
Chart.defaults.set('testscope', {test2: false});
expect(Chart.defaults.testscope.test).toEqual(true);
expect(Chart.defaults.testscope.test2).toEqual(false);
Chart.defaults.set('testscope', {test2: undefined});
expect(Chart.defaults.testscope.test2).toEqual(true);
delete Chart.defaults.testscope;
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.element.tests.js | test/specs/core.element.tests.js | describe('Chart.element', function() {
describe('getProps', function() {
it('should return requested properties', function() {
const elem = new Chart.Element();
elem.x = 10;
elem.y = 1.5;
expect(elem.getProps(['x', 'y'])).toEqual(jasmine.objectContaining({x: 10, y: 1.5}));
expect(elem.getProps(['x', 'y'], true)).toEqual(jasmine.objectContaining({x: 10, y: 1.5}));
elem.$animations = {x: {active: () => true, _to: 20}};
expect(elem.getProps(['x', 'y'])).toEqual(jasmine.objectContaining({x: 10, y: 1.5}));
expect(elem.getProps(['x', 'y'], true)).toEqual(jasmine.objectContaining({x: 20, y: 1.5}));
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/plugin.title.tests.js | test/specs/plugin.title.tests.js | // Test the rectangle element
var Title = Chart.registry.getPlugin('title')._element;
describe('Plugin.title', function() {
describe('auto', jasmine.fixture.specs('plugin.title'));
it('Should have the correct default config', function() {
expect(Chart.defaults.plugins.title).toEqual({
align: 'center',
color: Chart.defaults.color,
display: false,
position: 'top',
fullSize: true,
weight: 2000,
font: {
weight: 'bold'
},
padding: 10,
text: ''
});
});
it('should update correctly', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = 'My title';
var title = new Title({
chart: chart,
options: options
});
title.update(400, 200);
expect(title.width).toEqual(0);
expect(title.height).toEqual(0);
// Now we have a height since we display
title.options.display = true;
title.update(400, 200);
expect(title.width).toEqual(400);
expect(title.height).toEqual(34.4);
});
it('should update correctly when vertical', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = 'My title';
options.position = 'left';
var title = new Title({
chart: chart,
options: options
});
title.update(200, 400);
expect(title.width).toEqual(0);
expect(title.height).toEqual(0);
// Now we have a height since we display
title.options.display = true;
title.update(200, 400);
expect(title.width).toEqual(34.4);
expect(title.height).toEqual(400);
});
it('should have the correct size when there are multiple lines of text', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = ['line1', 'line2'];
options.position = 'left';
options.display = true;
options.font.lineHeight = 1.5;
var title = new Title({
chart: chart,
options: options
});
title.update(200, 400);
expect(title.width).toEqual(56);
expect(title.height).toEqual(400);
});
it('should draw correctly horizontally', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var context = window.createMockContext();
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = 'My title';
var title = new Title({
chart: chart,
options: options,
ctx: context
});
title.update(400, 200);
title.draw();
expect(context.getCalls()).toEqual([]);
// Now we have a height since we display
title.options.display = true;
title.update(400, 200);
title.top = 50;
title.left = 100;
title.bottom = title.top + title.height;
title.right = title.left + title.width;
title.draw();
expect(context.getCalls()).toEqual([{
name: 'save',
args: []
}, {
name: 'setFont',
args: ["normal bold 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"],
}, {
name: 'translate',
args: [300, 67.2]
}, {
name: 'rotate',
args: [0]
}, {
name: 'setFillStyle',
args: ['#666']
}, {
name: 'setTextAlign',
args: ['center'],
}, {
name: 'setTextBaseline',
args: ['middle'],
}, {
name: 'fillText',
args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
}]);
});
it ('should draw correctly vertically', function() {
var chart = {
options: Chart.helpers.clone(Chart.defaults)
};
var context = window.createMockContext();
var options = Chart.helpers.clone(Chart.defaults.plugins.title);
options.text = 'My title';
options.position = 'left';
var title = new Title({
chart: chart,
options: options,
ctx: context
});
title.update(200, 400);
title.draw();
expect(context.getCalls()).toEqual([]);
// Now we have a height since we display
title.options.display = true;
title.update(200, 400);
title.top = 50;
title.left = 100;
title.bottom = title.top + title.height;
title.right = title.left + title.width;
title.draw();
expect(context.getCalls()).toEqual([{
name: 'save',
args: []
}, {
name: 'setFont',
args: ["normal bold 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"],
}, {
name: 'translate',
args: [117.2, 250]
}, {
name: 'rotate',
args: [-0.5 * Math.PI]
}, {
name: 'setFillStyle',
args: ['#666']
}, {
name: 'setTextAlign',
args: ['center'],
}, {
name: 'setTextBaseline',
args: ['middle'],
}, {
name: 'fillText',
args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
}]);
// Rotation is other way on right side
title.options.position = 'right';
// Reset call tracker
context.resetCalls();
title.update(200, 400);
title.top = 50;
title.left = 100;
title.bottom = title.top + title.height;
title.right = title.left + title.width;
title.draw();
expect(context.getCalls()).toEqual([{
name: 'save',
args: []
}, {
name: 'setFont',
args: ["normal bold 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"],
}, {
name: 'translate',
args: [117.2, 250]
}, {
name: 'rotate',
args: [0.5 * Math.PI]
}, {
name: 'setFillStyle',
args: ['#666']
}, {
name: 'setTextAlign',
args: ['center'],
}, {
name: 'setTextBaseline',
args: ['middle'],
}, {
name: 'fillText',
args: ['My title', 0, 0, 400]
}, {
name: 'restore',
args: []
}]);
});
describe('config update', function() {
it ('should update the options', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
plugins: {
title: {
display: true
}
}
}
});
expect(chart.titleBlock.options.display).toBe(true);
chart.options.plugins.title.display = false;
chart.update();
expect(chart.titleBlock.options.display).toBe(false);
});
it ('should update the associated layout item', function() {
var chart = acquireChart({
type: 'line',
data: {},
options: {
plugins: {
title: {
fullSize: true,
position: 'top',
weight: 150
}
}
}
});
expect(chart.titleBlock.fullSize).toBe(true);
expect(chart.titleBlock.position).toBe('top');
expect(chart.titleBlock.weight).toBe(150);
chart.options.plugins.title.fullSize = false;
chart.options.plugins.title.position = 'left';
chart.options.plugins.title.weight = 42;
chart.update();
expect(chart.titleBlock.fullSize).toBe(false);
expect(chart.titleBlock.position).toBe('left');
expect(chart.titleBlock.weight).toBe(42);
});
it ('should remove the title if the new options are false', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
}
});
expect(chart.titleBlock).not.toBe(undefined);
chart.options.plugins.title = false;
chart.update();
expect(chart.titleBlock).toBe(undefined);
});
it ('should create the title if the title options are changed to exist', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
plugins: {
title: false
}
}
});
expect(chart.titleBlock).toBe(undefined);
chart.options.plugins.title = {};
chart.update();
expect(chart.titleBlock).not.toBe(undefined);
expect(chart.titleBlock.options).toEqualOptions(Chart.defaults.plugins.title);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.curve.tests.js | test/specs/helpers.curve.tests.js | describe('Curve helper tests', function() {
let helpers;
beforeAll(function() {
helpers = window.Chart.helpers;
});
it('should spline curves', function() {
expect(helpers.splineCurve({
x: 0,
y: 0
}, {
x: 1,
y: 1
}, {
x: 2,
y: 0
}, 0)).toEqual({
previous: {
x: 1,
y: 1,
},
next: {
x: 1,
y: 1,
}
});
expect(helpers.splineCurve({
x: 0,
y: 0
}, {
x: 1,
y: 1
}, {
x: 2,
y: 0
}, 1)).toEqual({
previous: {
x: 0,
y: 1,
},
next: {
x: 2,
y: 1,
}
});
});
it('should spline curves with monotone cubic interpolation', function() {
var dataPoints = [
{x: 0, y: 0, skip: false},
{x: 3, y: 6, skip: false},
{x: 9, y: 6, skip: false},
{x: 12, y: 60, skip: false},
{x: 15, y: 60, skip: false},
{x: 18, y: 120, skip: false},
{x: null, y: null, skip: true},
{x: 21, y: 180, skip: false},
{x: 24, y: 120, skip: false},
{x: 27, y: 125, skip: false},
{x: 30, y: 105, skip: false},
{x: 33, y: 110, skip: false},
{x: 33, y: 110, skip: false},
{x: 36, y: 170, skip: false}
];
helpers.splineCurveMonotone(dataPoints);
expect(dataPoints).toEqual([{
x: 0,
y: 0,
skip: false,
cp2x: 1,
cp2y: 2
},
{
x: 3,
y: 6,
skip: false,
cp1x: 2,
cp1y: 6,
cp2x: 5,
cp2y: 6
},
{
x: 9,
y: 6,
skip: false,
cp1x: 7,
cp1y: 6,
cp2x: 10,
cp2y: 6
},
{
x: 12,
y: 60,
skip: false,
cp1x: 11,
cp1y: 60,
cp2x: 13,
cp2y: 60
},
{
x: 15,
y: 60,
skip: false,
cp1x: 14,
cp1y: 60,
cp2x: 16,
cp2y: 60
},
{
x: 18,
y: 120,
skip: false,
cp1x: 17,
cp1y: 100
},
{
x: null,
y: null,
skip: true
},
{
x: 21,
y: 180,
skip: false,
cp2x: 22,
cp2y: 160
},
{
x: 24,
y: 120,
skip: false,
cp1x: 23,
cp1y: 120,
cp2x: 25,
cp2y: 120
},
{
x: 27,
y: 125,
skip: false,
cp1x: 26,
cp1y: 125,
cp2x: 28,
cp2y: 125
},
{
x: 30,
y: 105,
skip: false,
cp1x: 29,
cp1y: 105,
cp2x: 31,
cp2y: 105
},
{
x: 33,
y: 110,
skip: false,
cp1x: 32,
cp1y: 110,
cp2x: 33,
cp2y: 110
},
{
x: 33,
y: 110,
skip: false,
cp1x: 33,
cp1y: 110,
cp2x: 34,
cp2y: 110
},
{
x: 36,
y: 170,
skip: false,
cp1x: 35,
cp1y: 150
}]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/platform.basic.tests.js | test/specs/platform.basic.tests.js | describe('Platform.basic', function() {
it('should automatically choose the BasicPlatform for offscreen canvas', function() {
const chart = acquireChart({type: 'line'}, {useOffscreenCanvas: true});
expect(chart.platform).toBeInstanceOf(Chart.platforms.BasicPlatform);
chart.destroy();
});
it('should disable animations', function() {
const chart = acquireChart({type: 'line', options: {animation: {}}}, {useOffscreenCanvas: true});
expect(chart.options.animation).toEqual(false);
chart.destroy();
});
it('supports choosing the BasicPlatform in a web worker', function(done) {
const canvas = document.createElement('canvas');
if (!canvas.transferControlToOffscreen) {
pending();
}
const offscreenCanvas = canvas.transferControlToOffscreen();
const worker = new Worker('base/test/BasicChartWebWorker.js');
worker.onmessage = (event) => {
worker.terminate();
const {type, errorMessage} = event.data;
if (type === 'error') {
done.fail(errorMessage);
} else if (type === 'success') {
expect(type).toEqual('success');
done();
} else {
done.fail('invalid message type sent by worker: ' + type);
}
};
worker.postMessage({type: 'initialize', canvas: offscreenCanvas}, [offscreenCanvas]);
});
describe('with offscreenCanvas', function() {
it('supports laying out a simple chart', function() {
const chart = acquireChart({
type: 'bar',
data: {
datasets: [
{data: [10, 5, 0, 25, 78, -10]}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
}
}, {
canvas: {
height: 150,
width: 250
},
useOffscreenCanvas: true,
});
expect(chart.platform).toBeInstanceOf(Chart.platforms.BasicPlatform);
expect(chart.chartArea.bottom).toBeCloseToPixel(120);
expect(chart.chartArea.left).toBeCloseToPixel(31);
expect(chart.chartArea.right).toBeCloseToPixel(250);
expect(chart.chartArea.top).toBeCloseToPixel(32);
});
it('supports resizing a chart', function() {
const chart = acquireChart({
type: 'bar',
data: {
datasets: [
{data: [10, 5, 0, 25, 78, -10]}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
}
}, {
canvas: {
height: 150,
width: 250
},
useOffscreenCanvas: true,
});
expect(chart.platform).toBeInstanceOf(Chart.platforms.BasicPlatform);
const canvasElement = chart.canvas;
canvasElement.height = 200;
canvasElement.width = 300;
chart.resize();
expect(chart.chartArea.bottom).toBeCloseToPixel(150);
expect(chart.chartArea.left).toBeCloseToPixel(31);
expect(chart.chartArea.right).toBeCloseToPixel(300);
expect(chart.chartArea.top).toBeCloseToPixel(32);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/plugin.legend.tests.js | test/specs/plugin.legend.tests.js | // Test the rectangle element
describe('Legend block tests', function() {
describe('auto', jasmine.fixture.specs('plugin.legend'));
it('should have the correct default config', function() {
expect(Chart.defaults.plugins.legend).toEqual({
display: true,
position: 'top',
align: 'center',
fullSize: true,
reverse: false,
weight: 1000,
// a callback that will handle
onClick: jasmine.any(Function),
onHover: null,
onLeave: null,
labels: {
color: jasmine.any(Function),
boxWidth: 40,
padding: 10,
generateLabels: jasmine.any(Function)
},
title: {
color: jasmine.any(Function),
display: false,
position: 'center',
text: '',
}
});
});
it('should update bar chart correctly', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: '#f31',
borderCapStyle: 'butt',
borderDash: [2, 2],
borderDashOffset: 5.5,
data: []
}, {
label: 'dataset2',
hidden: true,
borderJoinStyle: 'miter',
data: []
}, {
label: 'dataset3',
borderWidth: 10,
borderColor: 'green',
pointStyle: 'crossRot',
data: []
}],
labels: []
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset1',
borderRadius: undefined,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 0,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 0
}, {
text: 'dataset2',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: true,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 0,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 1
}, {
text: 'dataset3',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 10,
strokeStyle: 'green',
pointStyle: 'crossRot',
rotation: undefined,
textAlign: undefined,
datasetIndex: 2
}]);
});
it('should update line chart correctly', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: '#f31',
borderCapStyle: 'round',
borderDash: [2, 2],
borderDashOffset: 5.5,
data: []
}, {
label: 'dataset2',
hidden: true,
borderJoinStyle: 'round',
data: []
}, {
label: 'dataset3',
borderWidth: 10,
borderColor: 'green',
pointStyle: 'crossRot',
fill: false,
data: []
}],
labels: []
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset1',
borderRadius: undefined,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: 'round',
lineDash: [2, 2],
lineDashOffset: 5.5,
lineJoin: 'miter',
lineWidth: 3,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 0
}, {
text: 'dataset2',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: true,
lineCap: 'butt',
lineDash: [],
lineDashOffset: 0,
lineJoin: 'round',
lineWidth: 3,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 1
}, {
text: 'dataset3',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: false,
lineCap: 'butt',
lineDash: [],
lineDashOffset: 0,
lineJoin: 'miter',
lineWidth: 10,
strokeStyle: 'green',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 2
}]);
});
it('should reverse correctly', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: '#f31',
borderCapStyle: 'round',
borderDash: [2, 2],
borderDashOffset: 5.5,
data: []
}, {
label: 'dataset2',
hidden: true,
borderJoinStyle: 'round',
data: []
}, {
label: 'dataset3',
borderWidth: 10,
borderColor: 'green',
pointStyle: 'crossRot',
fill: false,
data: []
}],
labels: []
},
options: {
plugins: {
legend: {
reverse: true
}
}
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset3',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: false,
lineCap: 'butt',
lineDash: [],
lineDashOffset: 0,
lineJoin: 'miter',
lineWidth: 10,
strokeStyle: 'green',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 2
}, {
text: 'dataset2',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: true,
lineCap: 'butt',
lineDash: [],
lineDashOffset: 0,
lineJoin: 'round',
lineWidth: 3,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 1
}, {
text: 'dataset1',
borderRadius: undefined,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: 'round',
lineDash: [2, 2],
lineDashOffset: 5.5,
lineJoin: 'miter',
lineWidth: 3,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 0
}]);
});
it('should filter items', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: '#f31',
borderCapStyle: 'butt',
borderDash: [2, 2],
borderDashOffset: 5.5,
data: []
}, {
label: 'dataset2',
hidden: true,
borderJoinStyle: 'miter',
data: [],
legendHidden: true,
}, {
label: 'dataset3',
borderWidth: 10,
borderRadius: 10,
borderColor: 'green',
pointStyle: 'crossRot',
data: []
}],
labels: []
},
options: {
plugins: {
legend: {
labels: {
filter: function(legendItem, data) {
var dataset = data.datasets[legendItem.datasetIndex];
return !dataset.legendHidden;
}
}
}
}
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset1',
borderRadius: undefined,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 0,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 0
}, {
text: 'dataset3',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 10,
strokeStyle: 'green',
pointStyle: 'crossRot',
rotation: undefined,
textAlign: undefined,
datasetIndex: 2
}]);
});
it('should sort items', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: '#f31',
borderCapStyle: 'round',
borderDash: [2, 2],
borderDashOffset: 5.5,
data: []
}, {
label: 'dataset2',
hidden: true,
borderJoinStyle: 'round',
data: []
}, {
label: 'dataset3',
borderWidth: 10,
borderColor: 'green',
pointStyle: 'crossRot',
fill: false,
data: []
}],
labels: []
},
options: {
plugins: {
legend: {
labels: {
sort: function(a, b) {
return b.datasetIndex > a.datasetIndex ? 1 : -1;
}
}
}
}
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset3',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: false,
lineCap: 'butt',
lineDash: [],
lineDashOffset: 0,
lineJoin: 'miter',
lineWidth: 10,
strokeStyle: 'green',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 2
}, {
text: 'dataset2',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: true,
lineCap: 'butt',
lineDash: [],
lineDashOffset: 0,
lineJoin: 'round',
lineWidth: 3,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 1
}, {
text: 'dataset1',
borderRadius: undefined,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: 'round',
lineDash: [2, 2],
lineDashOffset: 5.5,
lineJoin: 'miter',
lineWidth: 3,
strokeStyle: 'rgba(0,0,0,0.1)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 0
}]);
});
it('should not throw when the label options are missing', function() {
var makeChart = function() {
window.acquireChart({
type: 'bar',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: '#f31',
borderCapStyle: 'butt',
borderDash: [2, 2],
borderDashOffset: 5.5,
data: []
}],
labels: []
},
options: {
plugins: {
legend: {
labels: false,
}
}
}
});
};
expect(makeChart).not.toThrow();
});
it('should not draw legend items outside of the chart bounds', function() {
var chart = window.acquireChart(
{
type: 'line',
data: {
datasets: [1, 2, 3].map(function(n) {
return {
label: 'dataset' + n,
data: []
};
}),
labels: []
},
options: {
plugins: {
legend: {
position: 'right'
}
}
}
},
{
canvas: {
width: 512,
height: 105
}
}
);
// Check some basic assertions about the test setup
expect(chart.width).toBe(512);
expect(chart.legend.legendHitBoxes.length).toBe(3);
// Check whether any legend items reach outside the established bounds
chart.legend.legendHitBoxes.forEach(function(item) {
expect(item.left + item.width).toBeLessThanOrEqual(chart.width);
});
});
it('should draw legend with multiline labels', function() {
const chart = window.acquireChart({
type: 'doughnut',
data: {
labels: [
'ABCDE',
[
'ABCDE',
'ABCDE',
],
[
'Some Text',
'Some Text',
'Some Text',
],
'ABCDE',
],
datasets: [
{
label: 'test',
data: [
73.42,
18.13,
7.54,
0.9,
0.0025,
1.8e-5,
],
backgroundColor: [
'#0078C2',
'#56CAF5',
'#B1E3F9',
'#FBBC8D',
'#F6A3BE',
'#4EC2C1',
],
},
],
},
options: {
plugins: {
legend: {
labels: {
usePointStyle: true,
pointStyle: 'rect',
},
position: 'right',
align: 'center',
maxWidth: 860,
},
},
aspectRatio: 3,
},
});
// Check some basic assertions about the test setup
expect(chart.legend.legendHitBoxes.length).toBe(4);
// Check whether any legend items reach outside the established bounds
chart.legend.legendHitBoxes.forEach(function(item) {
expect(item.left + item.width).toBeLessThanOrEqual(chart.width);
});
});
it('should draw items with a custom boxHeight', function() {
var chart = window.acquireChart(
{
type: 'line',
data: {
datasets: [{
label: 'dataset1',
data: []
}],
labels: []
},
options: {
plugins: {
legend: {
position: 'right',
labels: {
boxHeight: 40
}
}
}
}
},
{
canvas: {
width: 512,
height: 105
}
}
);
const hitBox = chart.legend.legendHitBoxes[0];
expect(hitBox.height).toBe(40);
});
it('should pick up the first item when the property is an array', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: ['#f31', '#666', '#14e'],
borderWidth: [5, 10, 15],
borderColor: ['red', 'green', 'blue'],
data: []
}],
labels: []
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset1',
borderRadius: undefined,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 5,
strokeStyle: 'red',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 0
}]);
});
it('should use the borderRadius in the legend', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: ['#f31', '#666', '#14e'],
borderWidth: [5, 10, 15],
borderColor: ['red', 'green', 'blue'],
borderRadius: 10,
data: []
}],
labels: []
},
options: {
plugins: {
legend: {
labels: {
useBorderRadius: true,
}
}
}
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset1',
borderRadius: 10,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 5,
strokeStyle: 'red',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 0
}]);
});
it('should use the value for the first item when the property is a function', function() {
var helpers = window.Chart.helpers;
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: function(ctx) {
var value = ctx.dataset.data[ctx.dataIndex] || 0;
return helpers.color({r: value * 10, g: 0, b: 0}).rgbString();
},
borderWidth: function(ctx) {
var value = ctx.dataset.data[ctx.dataIndex] || 0;
return value;
},
borderColor: function(ctx) {
var value = ctx.dataset.data[ctx.dataIndex] || 0;
return helpers.color({r: 255 - value * 10, g: 0, b: 0}).rgbString();
},
data: [5, 10, 15, 20]
}],
labels: ['A', 'B', 'C', 'D']
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset1',
borderRadius: undefined,
fillStyle: 'rgb(50, 0, 0)',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 5,
strokeStyle: 'rgb(205, 0, 0)',
pointStyle: undefined,
rotation: undefined,
textAlign: undefined,
datasetIndex: 0
}]);
});
it('should draw correctly when usePointStyle is true', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: '#f31',
borderCapStyle: 'butt',
borderDash: [2, 2],
borderDashOffset: 5.5,
borderWidth: 0,
borderColor: '#f31',
pointStyle: 'crossRot',
pointBackgroundColor: 'rgba(0,0,0,0.1)',
pointBorderWidth: 5,
pointBorderColor: 'green',
data: []
}, {
label: 'dataset2',
backgroundColor: '#f31',
borderJoinStyle: 'miter',
borderWidth: 2,
borderColor: '#f31',
pointStyle: 'crossRot',
pointRotation: 15,
data: []
}],
labels: []
},
options: {
plugins: {
legend: {
labels: {
usePointStyle: true
}
}
}
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset1',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 5,
strokeStyle: 'green',
pointStyle: 'crossRot',
rotation: 0,
textAlign: undefined,
datasetIndex: 0
}, {
text: 'dataset2',
borderRadius: undefined,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 2,
strokeStyle: '#f31',
pointStyle: 'crossRot',
rotation: 15,
textAlign: undefined,
datasetIndex: 1
}]);
});
it('should draw correctly when usePointStyle is true and pointStyle override is set', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
label: 'dataset1',
backgroundColor: '#f31',
borderCapStyle: 'butt',
borderDash: [2, 2],
borderDashOffset: 5.5,
borderWidth: 0,
borderColor: '#f31',
pointStyle: 'crossRot',
pointBackgroundColor: 'rgba(0,0,0,0.1)',
pointBorderWidth: 5,
pointBorderColor: 'green',
data: []
}, {
label: 'dataset2',
backgroundColor: '#f31',
borderJoinStyle: 'miter',
borderWidth: 2,
borderColor: '#f31',
pointStyle: 'crossRot',
pointRotation: 15,
data: []
}],
labels: []
},
options: {
plugins: {
legend: {
labels: {
usePointStyle: true,
pointStyle: 'star'
}
}
}
}
});
expect(chart.legend.legendItems).toEqual([{
text: 'dataset1',
borderRadius: undefined,
fillStyle: 'rgba(0,0,0,0.1)',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 5,
strokeStyle: 'green',
pointStyle: 'star',
rotation: 0,
textAlign: undefined,
datasetIndex: 0
}, {
text: 'dataset2',
borderRadius: undefined,
fillStyle: '#f31',
fontColor: '#666',
hidden: false,
lineCap: undefined,
lineDash: undefined,
lineDashOffset: undefined,
lineJoin: undefined,
lineWidth: 2,
strokeStyle: '#f31',
pointStyle: 'star',
rotation: 15,
textAlign: undefined,
datasetIndex: 1
}]);
});
it('should not crash when the legend defaults are false', function() {
const oldDefaults = Chart.defaults.plugins.legend;
Chart.defaults.set({
plugins: {
legend: false,
},
});
var chart = window.acquireChart({
type: 'doughnut',
data: {
datasets: [{
label: 'dataset1',
data: [1, 2, 3, 4]
}],
labels: ['', '', '', '']
},
});
expect(chart).toBeDefined();
Chart.defaults.set({
plugins: {
legend: oldDefaults,
},
});
});
it('should not read onClick from chart options', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'dataset',
backgroundColor: 'red',
borderColor: 'red',
data: [120, 23, 24, 45, 51]
}]
},
options: {
responsive: true,
onClick() { },
plugins: {
legend: {
display: true
}
}
}
});
expect(chart.legend.options.onClick).toBe(Chart.defaults.plugins.legend.onClick);
});
it('should read labels.color from chart options', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'dataset',
backgroundColor: 'red',
borderColor: 'red',
data: [120, 23, 24, 45, 51]
}]
},
options: {
responsive: true,
color: 'green',
plugins: {
legend: {
display: true
}
}
}
});
expect(chart.legend.options.labels.color).toBe('green');
expect(chart.legend.options.title.color).toBe('green');
});
describe('config update', function() {
it('should update the options', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
plugins: {
legend: {
display: true
}
}
}
});
expect(chart.legend.options.display).toBe(true);
chart.options.plugins.legend.display = false;
chart.update();
expect(chart.legend.options.display).toBe(false);
});
it('should update the associated layout item', function() {
var chart = acquireChart({
type: 'line',
data: {},
options: {
plugins: {
legend: {
fullSize: true,
position: 'top',
weight: 150
}
}
}
});
expect(chart.legend.fullSize).toBe(true);
expect(chart.legend.position).toBe('top');
expect(chart.legend.weight).toBe(150);
chart.options.plugins.legend.fullSize = false;
chart.options.plugins.legend.position = 'left';
chart.options.plugins.legend.weight = 42;
chart.update();
expect(chart.legend.fullSize).toBe(false);
expect(chart.legend.position).toBe('left');
expect(chart.legend.weight).toBe(42);
});
it('should remove the legend if the new options are false', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
}
});
expect(chart.legend).not.toBe(undefined);
chart.options.plugins.legend = false;
chart.update();
expect(chart.legend).toBe(undefined);
});
it('should create the legend if the legend options are changed to exist', function() {
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
plugins: {
legend: false
}
}
});
expect(chart.legend).toBe(undefined);
chart.options.plugins.legend = {};
chart.update();
expect(chart.legend).not.toBe(undefined);
expect(chart.legend.options).toEqualOptions(Object.assign({},
// replace scriptable options with resolved values
Chart.defaults.plugins.legend,
{
labels: {color: Chart.defaults.color},
title: {color: Chart.defaults.color}
}
));
});
});
describe('callbacks', function() {
it('should call onClick, onHover and onLeave at the correct times', async function() {
var clickItem = null;
var hoverItem = null;
var leaveItem = null;
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
plugins: {
legend: {
onClick: function(_, item) {
clickItem = item;
},
onHover: function(_, item) {
hoverItem = item;
},
onLeave: function(_, item) {
leaveItem = item;
}
}
}
}
});
var hb = chart.legend.legendHitBoxes[0];
var el = {
x: hb.left + (hb.width / 2),
y: hb.top + (hb.height / 2)
};
await jasmine.triggerMouseEvent(chart, 'click', el);
expect(clickItem).toBe(chart.legend.legendItems[0]);
await jasmine.triggerMouseEvent(chart, 'mousemove', el);
expect(hoverItem).toBe(chart.legend.legendItems[0]);
await jasmine.triggerMouseEvent(chart, 'mousemove', chart.getDatasetMeta(0).data[0]);
expect(leaveItem).toBe(chart.legend.legendItems[0]);
});
it('should call onLeave when the mouse leaves the canvas', async function() {
var hoverItem = null;
var leaveItem = null;
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100]
}]
},
options: {
plugins: {
legend: {
onHover: function(_, item) {
hoverItem = item;
},
onLeave: function(_, item) {
leaveItem = item;
}
}
}
}
});
var hb = chart.legend.legendHitBoxes[0];
var el = {
x: hb.left + (hb.width / 2),
y: hb.top + (hb.height / 2)
};
await jasmine.triggerMouseEvent(chart, 'mousemove', el);
expect(hoverItem).toBe(chart.legend.legendItems[0]);
await jasmine.triggerMouseEvent(chart, 'mouseout');
expect(leaveItem).toBe(chart.legend.legendItems[0]);
});
it('should call onClick for the correct item when in RTL mode', async function() {
var clickItem = null;
var chart = acquireChart({
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [{
data: [10, 20, 30, 100],
label: 'dataset 1'
}, {
data: [10, 20, 30, 100],
label: 'dataset 2'
}]
},
options: {
plugins: {
legend: {
onClick: function(_, item) {
clickItem = item;
},
}
}
}
});
var hb = chart.legend.legendHitBoxes[0];
var el = {
x: hb.left + (hb.width / 2),
y: hb.top + (hb.height / 2)
};
await jasmine.triggerMouseEvent(chart, 'click', el);
expect(clickItem).toBe(chart.legend.legendItems[0]);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/controller.polarArea.tests.js | test/specs/controller.polarArea.tests.js | describe('Chart.controllers.polarArea', function() {
describe('auto', jasmine.fixture.specs('controller.polarArea'));
it('should update the scale correctly when data visibility is changed', function() {
var expectedScaleMax = 1;
var chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [
{data: [100]}
],
labels: ['x']
}
});
chart.toggleDataVisibility(0);
chart.update();
expect(chart.scales.r.max).toBe(expectedScaleMax);
});
it('should be registered as dataset controller', function() {
expect(typeof Chart.controllers.polarArea).toBe('function');
});
it('should be constructed', function() {
var chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [
{data: []},
{data: []}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.type).toEqual('polarArea');
expect(meta.data).toEqual([]);
expect(meta.hidden).toBe(null);
expect(meta.controller).not.toBe(undefined);
expect(meta.controller.index).toBe(1);
meta.controller.updateIndex(0);
expect(meta.controller.index).toBe(0);
});
it('should create arc elements for each data item during initialization', function() {
var chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [
{data: []},
{data: [10, 15, 0, -4]}
],
labels: []
}
});
var meta = chart.getDatasetMeta(1);
expect(meta.data.length).toBe(4); // 4 arcs created
expect(meta.data[0] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.ArcElement).toBe(true);
});
it('should draw all elements', function() {
var chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
}
});
var meta = chart.getDatasetMeta(0);
spyOn(meta.data[0], 'draw');
spyOn(meta.data[1], 'draw');
spyOn(meta.data[2], 'draw');
spyOn(meta.data[3], 'draw');
chart.update();
expect(meta.data[0].draw.calls.count()).toBe(1);
expect(meta.data[1].draw.calls.count()).toBe(1);
expect(meta.data[2].draw.calls.count()).toBe(1);
expect(meta.data[3].draw.calls.count()).toBe(1);
});
it('should update elements when modifying data', function() {
var chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
showLine: true,
plugins: {
legend: false,
title: false
},
elements: {
arc: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 255, 0)',
borderWidth: 1.2
}
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4);
[
{o: 174, s: -0.5 * Math.PI, e: 0},
{o: 236, s: 0, e: 0.5 * Math.PI},
{o: 51, s: 0.5 * Math.PI, e: Math.PI},
{o: 0, s: Math.PI, e: 1.5 * Math.PI}
].forEach(function(expected, i) {
expect(meta.data[i].x).withContext(i).toBeCloseToPixel(256);
expect(meta.data[i].y).withContext(i).toBeCloseToPixel(256);
expect(meta.data[i].innerRadius).withContext(i).toBeCloseToPixel(0);
expect(meta.data[i].outerRadius).withContext(i).toBeCloseToPixel(expected.o);
expect(meta.data[i].startAngle).withContext(i).toBe(expected.s);
expect(meta.data[i].endAngle).withContext(i).toBe(expected.e);
expect(meta.data[i].options).withContext(i).toEqual(jasmine.objectContaining({
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 255, 0)',
borderWidth: 1.2
}));
});
// arc styles
chart.data.datasets[0].backgroundColor = 'rgb(128, 129, 130)';
chart.data.datasets[0].borderColor = 'rgb(56, 57, 58)';
chart.data.datasets[0].borderWidth = 1.123;
chart.update();
for (var i = 0; i < 4; ++i) {
expect(meta.data[i].options.backgroundColor).toBe('rgb(128, 129, 130)');
expect(meta.data[i].options.borderColor).toBe('rgb(56, 57, 58)');
expect(meta.data[i].options.borderWidth).toBe(1.123);
}
chart.update();
expect(meta.data[0].x).toBeCloseToPixel(256);
expect(meta.data[0].y).toBeCloseToPixel(256);
expect(meta.data[0].innerRadius).toBeCloseToPixel(0);
expect(meta.data[0].outerRadius).toBeCloseToPixel(174);
});
it('should update elements with start angle from options', function() {
var chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
showLine: true,
plugins: {
legend: false,
title: false,
},
scales: {
r: {
startAngle: 90, // default is 0
}
},
elements: {
arc: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 255, 0)',
borderWidth: 1.2
}
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4);
[
{o: 174, s: 0, e: 0.5 * Math.PI},
{o: 236, s: 0.5 * Math.PI, e: Math.PI},
{o: 51, s: Math.PI, e: 1.5 * Math.PI},
{o: 0, s: 1.5 * Math.PI, e: 2.0 * Math.PI}
].forEach(function(expected, i) {
expect(meta.data[i].x).withContext(i).toBeCloseToPixel(256);
expect(meta.data[i].y).withContext(i).toBeCloseToPixel(256);
expect(meta.data[i].innerRadius).withContext(i).toBeCloseToPixel(0);
expect(meta.data[i].outerRadius).withContext(i).toBeCloseToPixel(expected.o);
expect(meta.data[i].startAngle).withContext(i).toBe(expected.s);
expect(meta.data[i].endAngle).withContext(i).toBe(expected.e);
expect(meta.data[i].options).withContext(i).toEqual(jasmine.objectContaining({
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 255, 0)',
borderWidth: 1.2
}));
});
});
it('should handle number of data point changes in update', function() {
var chart = window.acquireChart({
type: 'polarArea',
data: {
datasets: [{
data: [10, 15, 0, -4],
label: 'dataset2'
}],
labels: ['label1', 'label2', 'label3', 'label4']
},
options: {
showLine: true,
elements: {
arc: {
backgroundColor: 'rgb(255, 0, 0)',
borderColor: 'rgb(0, 255, 0)',
borderWidth: 1.2
}
}
}
});
var meta = chart.getDatasetMeta(0);
expect(meta.data.length).toBe(4);
// remove 2 items
chart.data.labels = ['label1', 'label2'];
chart.data.datasets[0].data = [1, 2];
chart.update();
expect(meta.data.length).toBe(2);
expect(meta.data[0] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.ArcElement).toBe(true);
// add 3 items
chart.data.labels = ['label1', 'label2', 'label3', 'label4', 'label5'];
chart.data.datasets[0].data = [1, 2, 3, 4, 5];
chart.update();
expect(meta.data.length).toBe(5);
expect(meta.data[0] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[1] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[2] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[3] instanceof Chart.elements.ArcElement).toBe(true);
expect(meta.data[4] instanceof Chart.elements.ArcElement).toBe(true);
});
describe('Interactions', function() {
beforeEach(function() {
this.chart = window.acquireChart({
type: 'polarArea',
data: {
labels: ['label1', 'label2', 'label3', 'label4'],
datasets: [{
data: [10, 15, 0, 4]
}]
},
options: {
cutoutPercentage: 0,
elements: {
arc: {
backgroundColor: 'rgb(100, 150, 200)',
borderColor: 'rgb(50, 100, 150)',
borderWidth: 2,
}
}
}
});
});
it('should handle default hover styles', async function() {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', arc);
expect(arc.options.backgroundColor).toBe('#3187DD');
expect(arc.options.borderColor).toBe('#175A9D');
expect(arc.options.borderWidth).toBe(2);
await jasmine.triggerMouseEvent(chart, 'mouseout', arc);
expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
expect(arc.options.borderWidth).toBe(2);
});
it('should handle hover styles defined via dataset properties', async function() {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.data.datasets[0], {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', arc);
expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
expect(arc.options.borderWidth).toBe(8.4);
await jasmine.triggerMouseEvent(chart, 'mouseout', arc);
expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
expect(arc.options.borderWidth).toBe(2);
});
it('should handle hover styles defined via element options', async function() {
var chart = this.chart;
var arc = chart.getDatasetMeta(0).data[0];
Chart.helpers.merge(chart.options.elements.arc, {
hoverBackgroundColor: 'rgb(200, 100, 150)',
hoverBorderColor: 'rgb(150, 50, 100)',
hoverBorderWidth: 8.4,
});
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', arc);
expect(arc.options.backgroundColor).toBe('rgb(200, 100, 150)');
expect(arc.options.borderColor).toBe('rgb(150, 50, 100)');
expect(arc.options.borderWidth).toBe(8.4);
await jasmine.triggerMouseEvent(chart, 'mouseout', arc);
expect(arc.options.backgroundColor).toBe('rgb(100, 150, 200)');
expect(arc.options.borderColor).toBe('rgb(50, 100, 150)');
expect(arc.options.borderWidth).toBe(2);
});
});
it('should not override tooltip title and label callbacks', async() => {
const chart = window.acquireChart({
type: 'polarArea',
data: {
labels: ['Label 1', 'Label 2'],
datasets: [{
data: [21, 79],
label: 'Dataset 1'
}, {
data: [33, 67],
label: 'Dataset 2'
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
}
});
const {tooltip} = chart;
const point = chart.getDatasetMeta(0).data[0];
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Label 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Dataset 1: 21'],
after: []
}]);
chart.options.plugins.tooltip = {mode: 'dataset'};
chart.update();
await jasmine.triggerMouseEvent(chart, 'mousemove', point);
expect(tooltip.title).toEqual(['Dataset 1']);
expect(tooltip.body).toEqual([{
before: [],
lines: ['Label 1: 21'],
after: []
}, {
before: [],
lines: ['Label 2: 79'],
after: []
}]);
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.ticks.tests.js | test/specs/core.ticks.tests.js | function getLabels(scale) {
return scale.ticks.map(t => t.label);
}
describe('Test tick generators', function() {
// formatters are used as default config values so users want to be able to reference them
it('Should expose formatters api', function() {
expect(typeof Chart.Ticks).toBeDefined();
expect(typeof Chart.Ticks.formatters).toBeDefined();
expect(typeof Chart.Ticks.formatters.values).toBe('function');
expect(typeof Chart.Ticks.formatters.numeric).toBe('function');
});
it('Should generate linear spaced ticks with correct precision', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: []
}],
},
options: {
plugins: {
legend: false
},
scales: {
x: {
type: 'linear',
position: 'bottom',
ticks: {
callback: function(value) {
return value.toString();
}
}
},
y: {
type: 'linear',
ticks: {
callback: function(value) {
return value.toString();
}
}
}
}
}
});
var xLabels = getLabels(chart.scales.x);
var yLabels = getLabels(chart.scales.y);
expect(xLabels).toEqual(['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']);
expect(yLabels).toEqual(['0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']);
});
it('Should generate logarithmic spaced ticks with correct precision', function() {
var chart = window.acquireChart({
type: 'line',
data: {
datasets: [{
data: []
}],
},
options: {
plugins: {
legend: false
},
scales: {
x: {
type: 'logarithmic',
position: 'bottom',
min: 0.1,
max: 1,
ticks: {
autoSkip: false,
callback: function(value) {
return value.toString();
}
}
},
y: {
type: 'logarithmic',
min: 0.1,
max: 1,
ticks: {
autoSkip: false,
callback: function(value) {
return value.toString();
}
}
}
}
}
});
var xLabels = getLabels(chart.scales.x);
var yLabels = getLabels(chart.scales.y);
expect(xLabels).toEqual(['0.1', '0.11', '0.12', '0.13', '0.14', '0.15', '0.16', '0.17', '0.18', '0.19', '0.2', '0.25', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']);
expect(yLabels).toEqual(['0.1', '0.11', '0.12', '0.13', '0.14', '0.15', '0.16', '0.17', '0.18', '0.19', '0.2', '0.25', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1']);
});
describe('formatters.numeric', function() {
it('should not fail on empty or 1 item array', function() {
const scale = {chart: {options: {locale: 'en'}}, options: {ticks: {format: {}}}};
expect(Chart.Ticks.formatters.numeric.apply(scale, [1, 0, []])).toEqual('1');
expect(Chart.Ticks.formatters.numeric.apply(scale, [1, 0, [{value: 1}]])).toEqual('1');
expect(Chart.Ticks.formatters.numeric.apply(scale, [1, 0, [{value: 1}, {value: 1.01}]])).toEqual('1.00');
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/helpers.canvas.tests.js | test/specs/helpers.canvas.tests.js | 'use strict';
describe('Chart.helpers.canvas', function() {
describe('auto', jasmine.fixture.specs('helpers'));
var helpers = Chart.helpers;
describe('clearCanvas', function() {
it('should clear the chart canvas', function() {
var chart = acquireChart({}, {
canvas: {
style: 'width: 150px; height: 245px'
}
});
spyOn(chart.ctx, 'clearRect');
helpers.clearCanvas(chart.canvas, chart.ctx);
expect(chart.ctx.clearRect.calls.count()).toBe(1);
expect(chart.ctx.clearRect.calls.first().object).toBe(chart.ctx);
expect(chart.ctx.clearRect.calls.first().args).toEqual([0, 0, 150, 245]);
});
it('should not throw error when chart is null', function() {
function createAndClearChart() {
var chart = acquireChart({}, {
canvas: null
});
// explicitly set canvas and ctx to null since setting it in acquireChart doesn't do anything
chart.canvas = null;
chart.ctx = null;
helpers.clearCanvas(chart.canvas, chart.ctx);
}
expect(createAndClearChart).not.toThrow();
});
});
describe('isPointInArea', function() {
it('should return true when no area is provided', function() {
expect(helpers._isPointInArea({x: 1, y: 1})).toBe(true);
});
it('should determine if a point is in the area', function() {
var isPointInArea = helpers._isPointInArea;
var area = {left: 0, top: 0, right: 512, bottom: 256};
expect(isPointInArea({x: 0, y: 0}, area)).toBe(true);
expect(isPointInArea({x: -1e-12, y: -1e-12}, area)).toBe(true);
expect(isPointInArea({x: 512, y: 256}, area)).toBe(true);
expect(isPointInArea({x: 512 + 1e-12, y: 256 + 1e-12}, area)).toBe(true);
expect(isPointInArea({x: -0.5, y: 0}, area)).toBe(false);
expect(isPointInArea({x: 0, y: 256.5}, area)).toBe(false);
});
});
it('should return the width of the longest text in an Array and 2D Array', function() {
var context = window.createMockContext();
var font = "normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
var arrayOfThings1D = ['FooBar', 'Bar'];
var arrayOfThings2D = [['FooBar_1', 'Bar_2'], 'Foo_1'];
// Regardless 'FooBar' is the longest label it should return (characters * 10)
expect(helpers._longestText(context, font, arrayOfThings1D, {})).toEqual(60);
expect(helpers._longestText(context, font, arrayOfThings2D, {})).toEqual(80);
// We check to make sure we made the right calls to the canvas.
expect(context.getCalls()).toEqual([{
name: 'save',
args: []
}, {
name: 'setFont',
args: ["normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"],
}, {
name: 'measureText',
args: ['FooBar']
}, {
name: 'measureText',
args: ['Bar']
}, {
name: 'restore',
args: []
}, {
name: 'save',
args: []
}, {
name: 'setFont',
args: ["normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"],
}, {
name: 'measureText',
args: ['FooBar_1']
}, {
name: 'measureText',
args: ['Bar_2']
}, {
name: 'measureText',
args: ['Foo_1']
}, {
name: 'restore',
args: []
}]);
});
it('compare text with current longest and update', function() {
var context = window.createMockContext();
var data = {};
var gc = [];
var longest = 70;
expect(helpers._measureText(context, data, gc, longest, 'foobar')).toEqual(70);
expect(helpers._measureText(context, data, gc, longest, 'foobar_')).toEqual(70);
expect(helpers._measureText(context, data, gc, longest, 'foobar_1')).toEqual(80);
// We check to make sure we made the right calls to the canvas.
expect(context.getCalls()).toEqual([{
name: 'measureText',
args: ['foobar']
}, {
name: 'measureText',
args: ['foobar_']
}, {
name: 'measureText',
args: ['foobar_1']
}]);
});
describe('renderText', function() {
it('should render multiple lines of text', function() {
var context = window.createMockContext();
var font = {string: '12px arial', lineHeight: 20};
helpers.renderText(context, ['foo', 'foo2'], 0, 0, font);
expect(context.getCalls()).toEqual([{
name: 'save',
args: [],
}, {
name: 'setFont',
args: ['12px arial'],
}, {
name: 'fillText',
args: ['foo', 0, 0, undefined],
}, {
name: 'fillText',
args: ['foo2', 0, 20, undefined],
}, {
name: 'restore',
args: [],
}]);
});
it('should accept the text maxWidth', function() {
var context = window.createMockContext();
var font = {string: '12px arial', lineHeight: 20};
helpers.renderText(context, 'foo', 0, 0, font, {maxWidth: 30});
expect(context.getCalls()).toEqual([{
name: 'save',
args: [],
}, {
name: 'setFont',
args: ['12px arial'],
}, {
name: 'fillText',
args: ['foo', 0, 0, 30],
}, {
name: 'restore',
args: [],
}]);
});
it('should underline the text', function() {
var context = window.createMockContext();
var font = {string: '12px arial', lineHeight: 20};
helpers.renderText(context, 'foo', 0, 0, font, {decorationWidth: 3, underline: true});
expect(context.getCalls()).toEqual([{
name: 'save',
args: [],
}, {
name: 'setFont',
args: ['12px arial'],
}, {
name: 'fillText',
args: ['foo', 0, 0, undefined],
}, {
name: 'measureText',
args: ['foo'],
}, {
name: 'setStrokeStyle',
args: [null],
}, {
name: 'beginPath',
args: [],
}, {
name: 'setLineWidth',
args: [3],
}, {
name: 'moveTo',
args: [-15, 8],
}, {
name: 'lineTo',
args: [25, 8],
}, {
name: 'stroke',
args: [],
}, {
name: 'restore',
args: [],
}]);
});
it('should strikethrough the text', function() {
var context = window.createMockContext();
var font = {string: '12px arial', lineHeight: 20};
helpers.renderText(context, 'foo', 0, 0, font, {strikethrough: true});
expect(context.getCalls()).toEqual([{
name: 'save',
args: [],
}, {
name: 'setFont',
args: ['12px arial'],
}, {
name: 'fillText',
args: ['foo', 0, 0, undefined],
}, {
name: 'measureText',
args: ['foo'],
}, {
name: 'setStrokeStyle',
args: [null],
}, {
name: 'beginPath',
args: [],
}, {
name: 'setLineWidth',
args: [2],
}, {
name: 'moveTo',
args: [-15, 2],
}, {
name: 'lineTo',
args: [25, 2],
}, {
name: 'stroke',
args: [],
}, {
name: 'restore',
args: [],
}]);
});
it('should set the fill style if supplied', function() {
var context = window.createMockContext();
var font = {string: '12px arial', lineHeight: 20};
helpers.renderText(context, 'foo', 0, 0, font, {color: 'red'});
expect(context.getCalls()).toEqual([{
name: 'save',
args: [],
}, {
name: 'setFont',
args: ['12px arial'],
}, {
name: 'setFillStyle',
args: ['red'],
}, {
name: 'fillText',
args: ['foo', 0, 0, undefined],
}, {
name: 'restore',
args: [],
}]);
});
it('should set the stroke style if supplied', function() {
var context = window.createMockContext();
var font = {string: '12px arial', lineHeight: 20};
helpers.renderText(context, 'foo', 0, 0, font, {strokeColor: 'red', strokeWidth: 2});
expect(context.getCalls()).toEqual([{
name: 'save',
args: [],
}, {
name: 'setFont',
args: ['12px arial'],
}, {
name: 'setStrokeStyle',
args: ['red'],
}, {
name: 'setLineWidth',
args: [2],
}, {
name: 'strokeText',
args: ['foo', 0, 0, undefined],
}, {
name: 'fillText',
args: ['foo', 0, 0, undefined],
}, {
name: 'restore',
args: [],
}]);
});
it('should set the text alignment', function() {
var context = window.createMockContext();
var font = {string: '12px arial', lineHeight: 20};
helpers.renderText(context, 'foo', 0, 0, font, {textAlign: 'left', textBaseline: 'middle'});
expect(context.getCalls()).toEqual([{
name: 'save',
args: [],
}, {
name: 'setFont',
args: ['12px arial'],
}, {
name: 'setTextAlign',
args: ['left'],
}, {
name: 'setTextBaseline',
args: ['middle'],
}, {
name: 'fillText',
args: ['foo', 0, 0, undefined],
}, {
name: 'restore',
args: [],
}]);
});
it('should translate and rotate text', function() {
var context = window.createMockContext();
var font = {string: '12px arial', lineHeight: 20};
helpers.renderText(context, 'foo', 0, 0, font, {rotation: 90, translation: [10, 20]});
expect(context.getCalls()).toEqual([{
name: 'save',
args: [],
}, {
name: 'setFont',
args: ['12px arial'],
}, {
name: 'translate',
args: [10, 20],
}, {
name: 'rotate',
args: [90],
}, {
name: 'fillText',
args: ['foo', 0, 0, undefined],
}, {
name: 'restore',
args: [],
}]);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/test/specs/core.layouts.tests.js | test/specs/core.layouts.tests.js | function getLabels(scale) {
return scale.ticks.map(t => t.label);
}
describe('Chart.layouts', function() {
describe('auto', jasmine.fixture.specs('core.layouts'));
it('should be exposed through Chart.layouts', function() {
expect(Chart.layouts).toBeDefined();
expect(typeof Chart.layouts).toBe('object');
expect(Chart.layouts.addBox).toBeDefined();
expect(Chart.layouts.removeBox).toBeDefined();
expect(Chart.layouts.configure).toBeDefined();
expect(Chart.layouts.update).toBeDefined();
});
it('should fit a simple chart with 2 scales', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [10, 5, 0, 25, 78, -10]}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
}
}, {
canvas: {
height: 150,
width: 250
}
});
expect(chart.chartArea.bottom).toBeCloseToPixel(120);
expect(chart.chartArea.left).toBeCloseToPixel(31);
expect(chart.chartArea.right).toBeCloseToPixel(250);
expect(chart.chartArea.top).toBeCloseToPixel(32);
// Is xScale at the right spot
expect(chart.scales.x.bottom).toBeCloseToPixel(150);
expect(chart.scales.x.left).toBeCloseToPixel(31);
expect(chart.scales.x.right).toBeCloseToPixel(250);
expect(chart.scales.x.top).toBeCloseToPixel(120);
expect(chart.scales.x.labelRotation).toBeCloseTo(0);
// Is yScale at the right spot
expect(chart.scales.y.bottom).toBeCloseToPixel(120);
expect(chart.scales.y.left).toBeCloseToPixel(0);
expect(chart.scales.y.right).toBeCloseToPixel(31);
expect(chart.scales.y.top).toBeCloseToPixel(32);
expect(chart.scales.y.labelRotation).toBeCloseTo(0);
});
it('should fit scales that are in the top and right positions', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{data: [10, 5, 0, 25, 78, -10]}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
scales: {
x: {
type: 'category',
position: 'top'
},
y: {
type: 'linear',
position: 'right'
}
}
}
}, {
canvas: {
height: 150,
width: 250
}
});
expect(chart.chartArea.bottom).toBeCloseToPixel(139);
expect(chart.chartArea.left).toBeCloseToPixel(0);
expect(chart.chartArea.right).toBeCloseToPixel(218);
expect(chart.chartArea.top).toBeCloseToPixel(62);
// Is xScale at the right spot
expect(chart.scales.x.bottom).toBeCloseToPixel(62);
expect(chart.scales.x.left).toBeCloseToPixel(0);
expect(chart.scales.x.right).toBeCloseToPixel(218);
expect(chart.scales.x.top).toBeCloseToPixel(32);
expect(chart.scales.x.labelRotation).toBeCloseTo(0);
// Is yScale at the right spot
expect(chart.scales.y.bottom).toBeCloseToPixel(139);
expect(chart.scales.y.left).toBeCloseToPixel(218);
expect(chart.scales.y.right).toBeCloseToPixel(250);
expect(chart.scales.y.top).toBeCloseToPixel(62);
expect(chart.scales.y.labelRotation).toBeCloseTo(0);
});
it('should fit scales that overlap the chart area', function() {
var chart = window.acquireChart({
type: 'radar',
data: {
datasets: [{
data: [10, 5, 0, 25, 78, -10]
}, {
data: [-19, -20, 0, -99, -50, 0]
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
}
});
expect(chart.chartArea.bottom).toBeCloseToPixel(512);
expect(chart.chartArea.left).toBeCloseToPixel(0);
expect(chart.chartArea.right).toBeCloseToPixel(512);
expect(chart.chartArea.top).toBeCloseToPixel(32);
var scale = chart.scales.r;
expect(scale.bottom).toBeCloseToPixel(512);
expect(scale.left).toBeCloseToPixel(0);
expect(scale.right).toBeCloseToPixel(512);
expect(scale.top).toBeCloseToPixel(32);
expect(scale.width).toBeCloseToPixel(496);
expect(scale.height).toBeCloseToPixel(464);
});
it('should fit multiple axes in the same position', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
yAxisID: 'y',
data: [10, 5, 0, 25, 78, -10]
}, {
yAxisID: 'y2',
data: [-19, -20, 0, -99, -50, 0]
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
scales: {
x: {
type: 'category'
},
y: {
type: 'linear'
},
y2: {
type: 'linear'
}
}
}
}, {
canvas: {
height: 150,
width: 250
}
});
expect(chart.chartArea.bottom).toBeCloseToPixel(110);
expect(chart.chartArea.left).toBeCloseToPixel(70);
expect(chart.chartArea.right).toBeCloseToPixel(250);
expect(chart.chartArea.top).toBeCloseToPixel(32);
// Is xScale at the right spot
expect(chart.scales.x.bottom).toBeCloseToPixel(150);
expect(chart.scales.x.left).toBeCloseToPixel(70);
expect(chart.scales.x.right).toBeCloseToPixel(250);
expect(chart.scales.x.top).toBeCloseToPixel(110);
expect(chart.scales.x.labelRotation).toBeCloseTo(40, -1);
// Are yScales at the right spot
expect(chart.scales.y.bottom).toBeCloseToPixel(110);
expect(chart.scales.y.left).toBeCloseToPixel(38);
expect(chart.scales.y.right).toBeCloseToPixel(70);
expect(chart.scales.y.top).toBeCloseToPixel(32);
expect(chart.scales.y.labelRotation).toBeCloseTo(0);
expect(chart.scales.y2.bottom).toBeCloseToPixel(110);
expect(chart.scales.y2.left).toBeCloseToPixel(0);
expect(chart.scales.y2.right).toBeCloseToPixel(38);
expect(chart.scales.y2.top).toBeCloseToPixel(32);
expect(chart.scales.y2.labelRotation).toBeCloseTo(0);
});
it ('should fit a full width box correctly', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [{
xAxisID: 'x',
data: [10, 5, 0, 25, 78, -10]
}, {
xAxisID: 'x2',
data: [-19, -20, 0, -99, -50, 0]
}],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
scales: {
x: {
type: 'category',
offset: false
},
x2: {
type: 'category',
position: 'top',
fullSize: true,
offset: false
},
y: {
type: 'linear'
}
}
}
});
expect(chart.chartArea.bottom).toBeCloseToPixel(484);
expect(chart.chartArea.left).toBeCloseToPixel(39);
expect(chart.chartArea.right).toBeCloseToPixel(496);
expect(chart.chartArea.top).toBeCloseToPixel(62);
// Are xScales at the right spot
expect(chart.scales.x.bottom).toBeCloseToPixel(512);
expect(chart.scales.x.left).toBeCloseToPixel(39);
expect(chart.scales.x.right).toBeCloseToPixel(496);
expect(chart.scales.x.top).toBeCloseToPixel(484);
expect(chart.scales.x2.bottom).toBeCloseToPixel(62);
expect(chart.scales.x2.left).toBeCloseToPixel(0);
expect(chart.scales.x2.right).toBeCloseToPixel(512);
expect(chart.scales.x2.top).toBeCloseToPixel(32);
// Is yScale at the right spot
expect(chart.scales.y.bottom).toBeCloseToPixel(484);
expect(chart.scales.y.left).toBeCloseToPixel(0);
expect(chart.scales.y.right).toBeCloseToPixel(39);
expect(chart.scales.y.top).toBeCloseToPixel(62);
});
describe('padding settings', function() {
it('should apply a single padding to all dimensions', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{
data: [10, 5, 0, 25, 78, -10]
}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false
}
},
plugins: {
legend: false,
title: false
},
layout: {
padding: 10
}
}
}, {
canvas: {
height: 150,
width: 250
}
});
expect(chart.chartArea.bottom).toBeCloseToPixel(140);
expect(chart.chartArea.left).toBeCloseToPixel(10);
expect(chart.chartArea.right).toBeCloseToPixel(240);
expect(chart.chartArea.top).toBeCloseToPixel(10);
});
it('should apply padding in all positions', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{
data: [10, 5, 0, 25, 78, -10]
}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false
}
},
plugins: {
legend: false,
title: false
},
layout: {
padding: {
left: 5,
right: 15,
top: 8,
bottom: 12
}
}
}
}, {
canvas: {
height: 150,
width: 250
}
});
expect(chart.chartArea.bottom).toBeCloseToPixel(138);
expect(chart.chartArea.left).toBeCloseToPixel(5);
expect(chart.chartArea.right).toBeCloseToPixel(235);
expect(chart.chartArea.top).toBeCloseToPixel(8);
});
it('should default to 0 padding if no dimensions specified', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{
data: [10, 5, 0, 25, 78, -10]
}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
scales: {
x: {
type: 'category',
display: false
},
y: {
type: 'linear',
display: false
}
},
plugins: {
legend: false,
title: false
},
layout: {
padding: {}
}
}
}, {
canvas: {
height: 150,
width: 250
}
});
expect(chart.chartArea.bottom).toBeCloseToPixel(150);
expect(chart.chartArea.left).toBeCloseToPixel(0);
expect(chart.chartArea.right).toBeCloseToPixel(250);
expect(chart.chartArea.top).toBeCloseToPixel(0);
});
});
describe('ordering by weight', function() {
it('should keep higher weights outside', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{
data: [10, 5, 0, 25, 78, -10]
}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
plugins: {
legend: {
display: true,
position: 'left',
},
title: {
display: true,
position: 'bottom',
},
}
},
}, {
canvas: {
height: 150,
width: 250
}
});
var xAxis = chart.scales.x;
var yAxis = chart.scales.y;
var legend = chart.legend;
var title = chart.titleBlock;
expect(yAxis.left).toBe(legend.right);
expect(xAxis.bottom).toBe(title.top);
});
it('should correctly set weights of scales and order them', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
datasets: [
{
data: [10, 5, 0, 25, 78, -10]
}
],
labels: ['tick1', 'tick2', 'tick3', 'tick4', 'tick5', 'tick6']
},
options: {
scales: {
x: {
type: 'category',
position: 'bottom',
display: true,
weight: 1
},
x1: {
type: 'category',
position: 'bottom',
display: true,
weight: 2
},
x2: {
type: 'category',
position: 'bottom',
display: true
},
x3: {
type: 'category',
display: true,
position: 'top',
weight: 1
},
x4: {
type: 'category',
display: true,
position: 'top',
weight: 2
},
y: {
type: 'linear',
display: true,
weight: 1
},
y1: {
type: 'linear',
position: 'left',
display: true,
weight: 2
},
y2: {
type: 'linear',
position: 'left',
display: true
},
y3: {
type: 'linear',
display: true,
position: 'right',
weight: 1
},
y4: {
type: 'linear',
display: true,
position: 'right',
weight: 2
}
}
}
}, {
canvas: {
height: 150,
width: 250
}
});
var xScale0 = chart.scales.x;
var xScale1 = chart.scales.x1;
var xScale2 = chart.scales.x2;
var xScale3 = chart.scales.x3;
var xScale4 = chart.scales.x4;
var yScale0 = chart.scales.y;
var yScale1 = chart.scales.y1;
var yScale2 = chart.scales.y2;
var yScale3 = chart.scales.y3;
var yScale4 = chart.scales.y4;
expect(xScale0.weight).toBe(1);
expect(xScale1.weight).toBe(2);
expect(xScale2.weight).toBe(0);
expect(xScale3.weight).toBe(1);
expect(xScale4.weight).toBe(2);
expect(yScale0.weight).toBe(1);
expect(yScale1.weight).toBe(2);
expect(yScale2.weight).toBe(0);
expect(yScale3.weight).toBe(1);
expect(yScale4.weight).toBe(2);
var isOrderCorrect = false;
// bottom axes
isOrderCorrect = xScale2.top < xScale0.top && xScale0.top < xScale1.top;
expect(isOrderCorrect).toBe(true);
// top axes
isOrderCorrect = xScale4.top < xScale3.top;
expect(isOrderCorrect).toBe(true);
// left axes
isOrderCorrect = yScale1.left < yScale0.left && yScale0.left < yScale2.left;
expect(isOrderCorrect).toBe(true);
// right axes
isOrderCorrect = yScale3.left < yScale4.left;
expect(isOrderCorrect).toBe(true);
});
});
describe('box sizing', function() {
it('should correctly compute y-axis width to fit labels', function() {
var chart = window.acquireChart({
type: 'bar',
data: {
labels: ['tick 1', 'tick 2', 'tick 3', 'tick 4', 'tick 5'],
datasets: [{
data: [0, 2.25, 1.5, 1.25, 2.5]
}],
},
options: {
plugins: {
legend: false
},
},
}, {
canvas: {
height: 256,
width: 256
}
});
var yAxis = chart.scales.y;
// issue #4441: y-axis labels partially hidden.
// minimum horizontal space required to fit labels
expect(yAxis.width).toBeCloseToPixel(30);
expect(getLabels(yAxis)).toEqual(['0', '0.5', '1.0', '1.5', '2.0', '2.5']);
});
});
});
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/docs/scripts/derived-bubble.js | docs/scripts/derived-bubble.js | import {Chart, BubbleController} from 'chart.js';
class Custom extends BubbleController {
draw() {
// Call bubble controller method to draw all the points
super.draw(arguments);
// Now we can do some custom drawing for this dataset.
// Here we'll draw a box around the first point in each dataset,
// using `boxStrokeStyle` dataset option for color
var meta = this.getMeta();
var pt0 = meta.data[0];
const {x, y} = pt0.getProps(['x', 'y']);
const {radius} = pt0.options;
var ctx = this.chart.ctx;
ctx.save();
ctx.strokeStyle = this.options.boxStrokeStyle;
ctx.lineWidth = 1;
ctx.strokeRect(x - radius, y - radius, 2 * radius, 2 * radius);
ctx.restore();
}
}
Custom.id = 'derivedBubble';
Custom.defaults = {
// Custom defaults. Bubble defaults are inherited.
boxStrokeStyle: 'red'
};
// Overrides are only inherited, but not merged if defined
// Custom.overrides = Chart.overrides.bubble;
// Stores the controller so that the chart initialization routine can look it up
Chart.register(Custom);
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/docs/scripts/log2.js | docs/scripts/log2.js | import {Scale, LinearScale} from 'chart.js';
export default class Log2Axis extends Scale {
constructor(cfg) {
super(cfg);
this._startValue = undefined;
this._valueRange = 0;
}
parse(raw, index) {
const value = LinearScale.prototype.parse.apply(this, [raw, index]);
return isFinite(value) && value > 0 ? value : null;
}
determineDataLimits() {
const {min, max} = this.getMinMax(true);
this.min = isFinite(min) ? Math.max(0, min) : null;
this.max = isFinite(max) ? Math.max(0, max) : null;
}
buildTicks() {
const ticks = [];
let power = Math.floor(Math.log2(this.min || 1));
let maxPower = Math.ceil(Math.log2(this.max || 2));
while (power <= maxPower) {
ticks.push({value: Math.pow(2, power)});
power += 1;
}
this.min = ticks[0].value;
this.max = ticks[ticks.length - 1].value;
return ticks;
}
/**
* @protected
*/
configure() {
const start = this.min;
super.configure();
this._startValue = Math.log2(start);
this._valueRange = Math.log2(this.max) - Math.log2(start);
}
getPixelForValue(value) {
if (value === undefined || value === 0) {
value = this.min;
}
return this.getPixelForDecimal(value === this.min ? 0
: (Math.log2(value) - this._startValue) / this._valueRange);
}
getValueForPixel(pixel) {
const decimal = this.getDecimalForPixel(pixel);
return Math.pow(2, this._startValue + decimal * this._valueRange);
}
}
Log2Axis.id = 'log2';
Log2Axis.defaults = {};
// The derived axis is registered like this:
// Chart.register(Log2Axis);
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/docs/scripts/register.js | docs/scripts/register.js | import {Chart, registerables} from '../../dist/chart.js';
import Log2Axis from './log2';
import './derived-bubble';
import analyzer from './analyzer';
Chart.register(...registerables);
Chart.register(Log2Axis);
Chart.register(analyzer);
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/docs/scripts/components.js | docs/scripts/components.js | // Add Chart components needed in samples here.
// Usable through `components[name]`.
export {Tooltip} from '../../dist/chart.js';
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/docs/scripts/analyzer.js | docs/scripts/analyzer.js | export default {
id: 'samples-filler-analyser',
beforeInit: function(chart, args, options) {
this.element = document.getElementById(options.target);
},
afterUpdate: function(chart) {
var datasets = chart.data.datasets;
var element = this.element;
var stats = [];
var meta, i, ilen, dataset;
if (!element) {
return;
}
for (i = 0, ilen = datasets.length; i < ilen; ++i) {
meta = chart.getDatasetMeta(i).$filler;
if (meta) {
dataset = datasets[i];
stats.push({
fill: dataset.fill,
target: meta.fill,
visible: meta.visible,
index: i
});
}
}
this.element.innerHTML = '<table>' +
'<tr>' +
'<th>Dataset</th>' +
'<th>Fill</th>' +
'<th>Target (visibility)</th>' +
'</tr>' +
stats.map(function(stat) {
var target = stat.target;
var row =
'<td><b>' + stat.index + '</b></td>' +
'<td>' + JSON.stringify(stat.fill) + '</td>';
if (target === false) {
target = 'none';
} else if (isFinite(target)) {
target = 'dataset ' + target;
} else {
target = 'boundary "' + target + '"';
}
if (stat.visible) {
row += '<td>' + target + '</td>';
} else {
row += '<td>(hidden)</td>';
}
return '<tr>' + row + '</tr>';
}).join('') + '</table>';
}
};
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/docs/scripts/helpers.js | docs/scripts/helpers.js | // Add helpers needed in samples here.
// Usable through `helpers[name]`.
export {color, getHoverColor, easingEffects} from '../../dist/helpers.js';
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/docs/scripts/utils.js | docs/scripts/utils.js | import colorLib from '@kurkle/color';
import {DateTime} from 'luxon';
import 'chartjs-adapter-luxon';
import {valueOrDefault} from '../../dist/helpers.js';
// Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
var _seed = Date.now();
export function srand(seed) {
_seed = seed;
}
export function rand(min, max) {
min = valueOrDefault(min, 0);
max = valueOrDefault(max, 0);
_seed = (_seed * 9301 + 49297) % 233280;
return min + (_seed / 233280) * (max - min);
}
export function numbers(config) {
var cfg = config || {};
var min = valueOrDefault(cfg.min, 0);
var max = valueOrDefault(cfg.max, 100);
var from = valueOrDefault(cfg.from, []);
var count = valueOrDefault(cfg.count, 8);
var decimals = valueOrDefault(cfg.decimals, 8);
var continuity = valueOrDefault(cfg.continuity, 1);
var dfactor = Math.pow(10, decimals) || 0;
var data = [];
var i, value;
for (i = 0; i < count; ++i) {
value = (from[i] || 0) + this.rand(min, max);
if (this.rand() <= continuity) {
data.push(Math.round(dfactor * value) / dfactor);
} else {
data.push(null);
}
}
return data;
}
export function points(config) {
const xs = this.numbers(config);
const ys = this.numbers(config);
return xs.map((x, i) => ({x, y: ys[i]}));
}
export function bubbles(config) {
return this.points(config).map(pt => {
pt.r = this.rand(config.rmin, config.rmax);
return pt;
});
}
export function labels(config) {
var cfg = config || {};
var min = cfg.min || 0;
var max = cfg.max || 100;
var count = cfg.count || 8;
var step = (max - min) / count;
var decimals = cfg.decimals || 8;
var dfactor = Math.pow(10, decimals) || 0;
var prefix = cfg.prefix || '';
var values = [];
var i;
for (i = min; i < max; i += step) {
values.push(prefix + Math.round(dfactor * i) / dfactor);
}
return values;
}
const MONTHS = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
export function months(config) {
var cfg = config || {};
var count = cfg.count || 12;
var section = cfg.section;
var values = [];
var i, value;
for (i = 0; i < count; ++i) {
value = MONTHS[Math.ceil(i) % 12];
values.push(value.substring(0, section));
}
return values;
}
const COLORS = [
'#4dc9f6',
'#f67019',
'#f53794',
'#537bc4',
'#acc236',
'#166a8f',
'#00a950',
'#58595b',
'#8549ba'
];
export function color(index) {
return COLORS[index % COLORS.length];
}
export function transparentize(value, opacity) {
var alpha = opacity === undefined ? 0.5 : 1 - opacity;
return colorLib(value).alpha(alpha).rgbString();
}
export const CHART_COLORS = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
const NAMED_COLORS = [
CHART_COLORS.red,
CHART_COLORS.orange,
CHART_COLORS.yellow,
CHART_COLORS.green,
CHART_COLORS.blue,
CHART_COLORS.purple,
CHART_COLORS.grey,
];
export function namedColor(index) {
return NAMED_COLORS[index % NAMED_COLORS.length];
}
export function newDate(days) {
return DateTime.now().plus({days}).toJSDate();
}
export function newDateString(days) {
return DateTime.now().plus({days}).toISO();
}
export function parseISODate(str) {
return DateTime.fromISO(str);
}
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
chartjs/Chart.js | https://github.com/chartjs/Chart.js/blob/a153556861074e827358446ec937555ac58c3d11/auto/auto.js | auto/auto.js | import {Chart, registerables} from '../dist/chart.js';
Chart.register(...registerables);
export * from '../dist/chart.js';
export default Chart;
| javascript | MIT | a153556861074e827358446ec937555ac58c3d11 | 2026-01-04T14:56:49.667758Z | false |
poteto/hiring-without-whiteboards | https://github.com/poteto/hiring-without-whiteboards/blob/cbf9a3a220a283cff906d785548c69b9dbe95a67/index.js | index.js | module.exports = {}; | javascript | MIT | cbf9a3a220a283cff906d785548c69b9dbe95a67 | 2026-01-04T14:57:26.793391Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/babel.config.js | babel.config.js | module.exports = {
env: {
test: {
presets: [
'@babel/preset-env'
]
},
build: {
presets: [
[
'@babel/preset-env',
{
modules: false,
loose: true
}
]
]
}
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/prettier.config.js | prettier.config.js | module.exports = {
useTabs: false,
printWidth: 80,
singleQuote: true,
trailingComma: 'none',
semi: false
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/karma.sauce.conf.js | karma.sauce.conf.js | module.exports = function (config) {
const batches = [
{
sl_chrome_26: {
base: 'SauceLabs',
browserName: 'chrome',
version: '26'
},
sl_chrome: {
base: 'SauceLabs',
browserName: 'chrome'
},
sl_firefox_4: {
base: 'SauceLabs',
browserName: 'firefox',
version: '4'
},
sl_firefox: {
base: 'SauceLabs',
browserName: 'firefox'
},
sl_mac_safari_8: {
base: 'SauceLabs',
browserName: 'safari',
version: '8',
platform: 'OS X 10.10'
},
sl_mac_safari: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'macOS 10.13'
}
},
{
sl_ie_9: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '9'
},
sl_ie: {
base: 'SauceLabs',
browserName: 'internet explorer'
},
sl_edge_13: {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10',
version: '13'
},
sl_edge: {
base: 'SauceLabs',
browserName: 'MicrosoftEdge'
}
},
{
sl_ios_safari_9: {
base: 'SauceLabs',
browserName: 'iphone',
version: '9.3'
},
sl_android_4_4: {
base: 'SauceLabs',
browserName: 'android',
version: '4.4'
}
},
{
sl_ios_safari: {
base: 'SauceLabs',
browserName: 'iphone'
},
sl_android: {
base: 'SauceLabs',
browserName: 'android'
}
}
]
const batch = batches[process.argv[4] || 0]
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'dayjs.min.js',
'test/*spec.js'
],
reporters: ['dots', 'saucelabs'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
sauceLabs: {
// build: 'Manual',
testName: 'Day.js'
},
captureTimeout: 200000, // try fix ios timeout
customLaunchers: batch,
browsers: Object.keys(batch),
singleRun: true
})
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/constant.js | src/constant.js | export const SECONDS_A_MINUTE = 60
export const SECONDS_A_HOUR = SECONDS_A_MINUTE * 60
export const SECONDS_A_DAY = SECONDS_A_HOUR * 24
export const SECONDS_A_WEEK = SECONDS_A_DAY * 7
export const MILLISECONDS_A_SECOND = 1e3
export const MILLISECONDS_A_MINUTE = SECONDS_A_MINUTE * MILLISECONDS_A_SECOND
export const MILLISECONDS_A_HOUR = SECONDS_A_HOUR * MILLISECONDS_A_SECOND
export const MILLISECONDS_A_DAY = SECONDS_A_DAY * MILLISECONDS_A_SECOND
export const MILLISECONDS_A_WEEK = SECONDS_A_WEEK * MILLISECONDS_A_SECOND
// English locales
export const MS = 'millisecond'
export const S = 'second'
export const MIN = 'minute'
export const H = 'hour'
export const D = 'day'
export const W = 'week'
export const M = 'month'
export const Q = 'quarter'
export const Y = 'year'
export const DATE = 'date'
export const FORMAT_DEFAULT = 'YYYY-MM-DDTHH:mm:ssZ'
export const INVALID_DATE_STRING = 'Invalid Date'
// regex
export const REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/
export const REGEX_FORMAT = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/index.js | src/index.js | import * as C from './constant'
import en from './locale/en'
import U from './utils'
let L = 'en' // global locale
const Ls = {} // global loaded locale
Ls[L] = en
const IS_DAYJS = '$isDayjsObject'
// eslint-disable-next-line no-use-before-define
const isDayjs = d => d instanceof Dayjs || !!(d && d[IS_DAYJS])
const parseLocale = (preset, object, isLocal) => {
let l
if (!preset) return L
if (typeof preset === 'string') {
const presetLower = preset.toLowerCase()
if (Ls[presetLower]) {
l = presetLower
}
if (object) {
Ls[presetLower] = object
l = presetLower
}
const presetSplit = preset.split('-')
if (!l && presetSplit.length > 1) {
return parseLocale(presetSplit[0])
}
} else {
const { name } = preset
Ls[name] = preset
l = name
}
if (!isLocal && l) L = l
return l || (!isLocal && L)
}
const dayjs = function (date, c) {
if (isDayjs(date)) {
return date.clone()
}
// eslint-disable-next-line no-nested-ternary
const cfg = typeof c === 'object' ? c : {}
cfg.date = date
cfg.args = arguments// eslint-disable-line prefer-rest-params
return new Dayjs(cfg) // eslint-disable-line no-use-before-define
}
const wrapper = (date, instance) =>
dayjs(date, {
locale: instance.$L,
utc: instance.$u,
x: instance.$x,
$offset: instance.$offset // todo: refactor; do not use this.$offset in you code
})
const Utils = U // for plugin use
Utils.l = parseLocale
Utils.i = isDayjs
Utils.w = wrapper
const parseDate = (cfg) => {
const { date, utc } = cfg
if (date === null) return new Date(NaN) // null is invalid
if (Utils.u(date)) return new Date() // today
if (date instanceof Date) return new Date(date)
if (typeof date === 'string' && !/Z$/i.test(date)) {
const d = date.match(C.REGEX_PARSE)
if (d) {
const m = d[2] - 1 || 0
const ms = (d[7] || '0').substring(0, 3)
if (utc) {
return new Date(Date.UTC(d[1], m, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, ms))
}
return new Date(d[1], m, d[3]
|| 1, d[4] || 0, d[5] || 0, d[6] || 0, ms)
}
}
return new Date(date) // everything else
}
class Dayjs {
constructor(cfg) {
this.$L = parseLocale(cfg.locale, null, true)
this.parse(cfg) // for plugin
this.$x = this.$x || cfg.x || {}
this[IS_DAYJS] = true
}
parse(cfg) {
this.$d = parseDate(cfg)
this.init()
}
init() {
const { $d } = this
this.$y = $d.getFullYear()
this.$M = $d.getMonth()
this.$D = $d.getDate()
this.$W = $d.getDay()
this.$H = $d.getHours()
this.$m = $d.getMinutes()
this.$s = $d.getSeconds()
this.$ms = $d.getMilliseconds()
}
// eslint-disable-next-line class-methods-use-this
$utils() {
return Utils
}
isValid() {
return !(this.$d.toString() === C.INVALID_DATE_STRING)
}
isSame(that, units) {
const other = dayjs(that)
return this.startOf(units) <= other && other <= this.endOf(units)
}
isAfter(that, units) {
return dayjs(that) < this.startOf(units)
}
isBefore(that, units) {
return this.endOf(units) < dayjs(that)
}
$g(input, get, set) {
if (Utils.u(input)) return this[get]
return this.set(set, input)
}
unix() {
return Math.floor(this.valueOf() / 1000)
}
valueOf() {
// timezone(hour) * 60 * 60 * 1000 => ms
return this.$d.getTime()
}
startOf(units, startOf) { // startOf -> endOf
const isStartOf = !Utils.u(startOf) ? startOf : true
const unit = Utils.p(units)
const instanceFactory = (d, m) => {
const ins = Utils.w(this.$u ?
Date.UTC(this.$y, m, d) : new Date(this.$y, m, d), this)
return isStartOf ? ins : ins.endOf(C.D)
}
const instanceFactorySet = (method, slice) => {
const argumentStart = [0, 0, 0, 0]
const argumentEnd = [23, 59, 59, 999]
return Utils.w(this.toDate()[method].apply( // eslint-disable-line prefer-spread
this.toDate('s'),
(isStartOf ? argumentStart : argumentEnd).slice(slice)
), this)
}
const { $W, $M, $D } = this
const utcPad = `set${this.$u ? 'UTC' : ''}`
switch (unit) {
case C.Y:
return isStartOf ? instanceFactory(1, 0) :
instanceFactory(31, 11)
case C.M:
return isStartOf ? instanceFactory(1, $M) :
instanceFactory(0, $M + 1)
case C.W: {
const weekStart = this.$locale().weekStart || 0
const gap = ($W < weekStart ? $W + 7 : $W) - weekStart
return instanceFactory(isStartOf ? $D - gap : $D + (6 - gap), $M)
}
case C.D:
case C.DATE:
return instanceFactorySet(`${utcPad}Hours`, 0)
case C.H:
return instanceFactorySet(`${utcPad}Minutes`, 1)
case C.MIN:
return instanceFactorySet(`${utcPad}Seconds`, 2)
case C.S:
return instanceFactorySet(`${utcPad}Milliseconds`, 3)
default:
return this.clone()
}
}
endOf(arg) {
return this.startOf(arg, false)
}
$set(units, int) { // private set
const unit = Utils.p(units)
const utcPad = `set${this.$u ? 'UTC' : ''}`
const name = {
[C.D]: `${utcPad}Date`,
[C.DATE]: `${utcPad}Date`,
[C.M]: `${utcPad}Month`,
[C.Y]: `${utcPad}FullYear`,
[C.H]: `${utcPad}Hours`,
[C.MIN]: `${utcPad}Minutes`,
[C.S]: `${utcPad}Seconds`,
[C.MS]: `${utcPad}Milliseconds`
}[unit]
const arg = unit === C.D ? this.$D + (int - this.$W) : int
if (unit === C.M || unit === C.Y) {
// clone is for badMutable plugin
const date = this.clone().set(C.DATE, 1)
date.$d[name](arg)
date.init()
this.$d = date.set(C.DATE, Math.min(this.$D, date.daysInMonth())).$d
} else if (name) this.$d[name](arg)
this.init()
return this
}
set(string, int) {
return this.clone().$set(string, int)
}
get(unit) {
return this[Utils.p(unit)]()
}
add(number, units) {
number = Number(number) // eslint-disable-line no-param-reassign
const unit = Utils.p(units)
const instanceFactorySet = (n) => {
const d = dayjs(this)
return Utils.w(d.date(d.date() + Math.round(n * number)), this)
}
if (unit === C.M) {
return this.set(C.M, this.$M + number)
}
if (unit === C.Y) {
return this.set(C.Y, this.$y + number)
}
if (unit === C.D) {
return instanceFactorySet(1)
}
if (unit === C.W) {
return instanceFactorySet(7)
}
const step = {
[C.MIN]: C.MILLISECONDS_A_MINUTE,
[C.H]: C.MILLISECONDS_A_HOUR,
[C.S]: C.MILLISECONDS_A_SECOND
}[unit] || 1 // ms
const nextTimeStamp = this.$d.getTime() + (number * step)
return Utils.w(nextTimeStamp, this)
}
subtract(number, string) {
return this.add(number * -1, string)
}
format(formatStr) {
const locale = this.$locale()
if (!this.isValid()) return locale.invalidDate || C.INVALID_DATE_STRING
const str = formatStr || C.FORMAT_DEFAULT
const zoneStr = Utils.z(this)
const { $H, $m, $M } = this
const {
weekdays, months, meridiem
} = locale
const getShort = (arr, index, full, length) => (
(arr && (arr[index] || arr(this, str))) || full[index].slice(0, length)
)
const get$H = num => (
Utils.s($H % 12 || 12, num, '0')
)
const meridiemFunc = meridiem || ((hour, minute, isLowercase) => {
const m = (hour < 12 ? 'AM' : 'PM')
return isLowercase ? m.toLowerCase() : m
})
const matches = (match) => {
switch (match) {
case 'YY':
return String(this.$y).slice(-2)
case 'YYYY':
return Utils.s(this.$y, 4, '0')
case 'M':
return $M + 1
case 'MM':
return Utils.s($M + 1, 2, '0')
case 'MMM':
return getShort(locale.monthsShort, $M, months, 3)
case 'MMMM':
return getShort(months, $M)
case 'D':
return this.$D
case 'DD':
return Utils.s(this.$D, 2, '0')
case 'd':
return String(this.$W)
case 'dd':
return getShort(locale.weekdaysMin, this.$W, weekdays, 2)
case 'ddd':
return getShort(locale.weekdaysShort, this.$W, weekdays, 3)
case 'dddd':
return weekdays[this.$W]
case 'H':
return String($H)
case 'HH':
return Utils.s($H, 2, '0')
case 'h':
return get$H(1)
case 'hh':
return get$H(2)
case 'a':
return meridiemFunc($H, $m, true)
case 'A':
return meridiemFunc($H, $m, false)
case 'm':
return String($m)
case 'mm':
return Utils.s($m, 2, '0')
case 's':
return String(this.$s)
case 'ss':
return Utils.s(this.$s, 2, '0')
case 'SSS':
return Utils.s(this.$ms, 3, '0')
case 'Z':
return zoneStr // 'ZZ' logic below
default:
break
}
return null
}
return str.replace(C.REGEX_FORMAT, (match, $1) => $1 || matches(match) || zoneStr.replace(':', '')) // 'ZZ'
}
utcOffset() {
// Because a bug at FF24, we're rounding the timezone offset around 15 minutes
// https://github.com/moment/moment/pull/1871
return -Math.round(this.$d.getTimezoneOffset() / 15) * 15
}
diff(input, units, float) {
const unit = Utils.p(units)
const that = dayjs(input)
const zoneDelta = (that.utcOffset() - this.utcOffset()) * C.MILLISECONDS_A_MINUTE
const diff = this - that
const getMonth = () => Utils.m(this, that)
let result
switch (unit) {
case C.Y:
result = getMonth() / 12
break
case C.M:
result = getMonth()
break
case C.Q:
result = getMonth() / 3
break
case C.W:
result = (diff - zoneDelta) / C.MILLISECONDS_A_WEEK
break
case C.D:
result = (diff - zoneDelta) / C.MILLISECONDS_A_DAY
break
case C.H:
result = diff / C.MILLISECONDS_A_HOUR
break
case C.MIN:
result = diff / C.MILLISECONDS_A_MINUTE
break
case C.S:
result = diff / C.MILLISECONDS_A_SECOND
break
default:
result = diff // milliseconds
break
}
return float ? result : Utils.a(result)
}
daysInMonth() {
return this.endOf(C.M).$D
}
$locale() { // get locale object
return Ls[this.$L]
}
locale(preset, object) {
if (!preset) return this.$L
const that = this.clone()
const nextLocaleName = parseLocale(preset, object, true)
if (nextLocaleName) that.$L = nextLocaleName
return that
}
clone() {
return Utils.w(this.$d, this)
}
toDate() {
return new Date(this.valueOf())
}
toJSON() {
return this.isValid() ? this.toISOString() : null
}
toISOString() {
// ie 8 return
// new Dayjs(this.valueOf() + this.$d.getTimezoneOffset() * 60000)
// .format('YYYY-MM-DDTHH:mm:ss.SSS[Z]')
return this.$d.toISOString()
}
toString() {
return this.$d.toUTCString()
}
}
const proto = Dayjs.prototype
dayjs.prototype = proto;
[
['$ms', C.MS],
['$s', C.S],
['$m', C.MIN],
['$H', C.H],
['$W', C.D],
['$M', C.M],
['$y', C.Y],
['$D', C.DATE]
].forEach((g) => {
proto[g[1]] = function (input) {
return this.$g(input, g[0], g[1])
}
})
dayjs.extend = (plugin, option) => {
if (!plugin.$i) { // install plugin only once
plugin(option, Dayjs, dayjs)
plugin.$i = true
}
return dayjs
}
dayjs.locale = parseLocale
dayjs.isDayjs = isDayjs
dayjs.unix = timestamp => (
dayjs(timestamp * 1e3)
)
dayjs.en = Ls[L]
dayjs.Ls = Ls
dayjs.p = {}
export default dayjs
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/utils.js | src/utils.js | import * as C from './constant'
const padStart = (string, length, pad) => {
const s = String(string)
if (!s || s.length >= length) return string
return `${Array((length + 1) - s.length).join(pad)}${string}`
}
const padZoneStr = (instance) => {
const negMinutes = -instance.utcOffset()
const minutes = Math.abs(negMinutes)
const hourOffset = Math.floor(minutes / 60)
const minuteOffset = minutes % 60
return `${negMinutes <= 0 ? '+' : '-'}${padStart(hourOffset, 2, '0')}:${padStart(minuteOffset, 2, '0')}`
}
const monthDiff = (a, b) => {
// function from moment.js in order to keep the same result
if (a.date() < b.date()) return -monthDiff(b, a)
const wholeMonthDiff = ((b.year() - a.year()) * 12) + (b.month() - a.month())
const anchor = a.clone().add(wholeMonthDiff, C.M)
const c = b - anchor < 0
const anchor2 = a.clone().add(wholeMonthDiff + (c ? -1 : 1), C.M)
return +(-(wholeMonthDiff + ((b - anchor) / (c ? (anchor - anchor2) :
(anchor2 - anchor)))) || 0)
}
const absFloor = n => (n < 0 ? Math.ceil(n) || 0 : Math.floor(n))
const prettyUnit = (u) => {
const special = {
M: C.M,
y: C.Y,
w: C.W,
d: C.D,
D: C.DATE,
h: C.H,
m: C.MIN,
s: C.S,
ms: C.MS,
Q: C.Q
}
return special[u] || String(u || '').toLowerCase().replace(/s$/, '')
}
const isUndefined = s => s === undefined
export default {
s: padStart,
z: padZoneStr,
m: monthDiff,
a: absFloor,
p: prettyUnit,
u: isUndefined
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/bigIntSupport/index.js | src/plugin/bigIntSupport/index.js | // eslint-disable-next-line valid-typeof
const isBigInt = num => typeof num === 'bigint'
export default (o, c, dayjs) => {
const proto = c.prototype
const parseDate = (cfg) => {
const { date } = cfg
if (isBigInt(date)) {
return Number(date)
}
return date
}
const oldParse = proto.parse
proto.parse = function (cfg) {
cfg.date = parseDate.bind(this)(cfg)
oldParse.bind(this)(cfg)
}
const oldUnix = dayjs.unix
dayjs.unix = function (timestamp) {
const ts = isBigInt(timestamp) ? Number(timestamp) : timestamp
return oldUnix(ts)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/updateLocale/index.js | src/plugin/updateLocale/index.js | export default (option, Dayjs, dayjs) => {
dayjs.updateLocale = function (locale, customConfig) {
const localeList = dayjs.Ls
const localeConfig = localeList[locale]
if (!localeConfig) return
const customConfigKeys = customConfig ? Object.keys(customConfig) : []
customConfigKeys.forEach((c) => {
localeConfig[c] = customConfig[c]
})
return localeConfig // eslint-disable-line consistent-return
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/localizedFormat/index.js | src/plugin/localizedFormat/index.js | import { FORMAT_DEFAULT } from '../../constant'
import { u, englishFormats } from './utils'
export default (o, c, d) => {
const proto = c.prototype
const oldFormat = proto.format
d.en.formats = englishFormats
proto.format = function (formatStr = FORMAT_DEFAULT) {
const { formats = {} } = this.$locale()
const result = u(formatStr, formats)
return oldFormat.call(this, result)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/localizedFormat/utils.js | src/plugin/localizedFormat/utils.js | // eslint-disable-next-line import/prefer-default-export
export const t = format =>
format.replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g, (_, a, b) => a || b.slice(1))
export const englishFormats = {
LTS: 'h:mm:ss A',
LT: 'h:mm A',
L: 'MM/DD/YYYY',
LL: 'MMMM D, YYYY',
LLL: 'MMMM D, YYYY h:mm A',
LLLL: 'dddd, MMMM D, YYYY h:mm A'
}
export const u = (formatStr, formats) => formatStr.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g, (_, a, b) => {
const B = b && b.toUpperCase()
return a || formats[b] || englishFormats[b] || t(formats[B])
})
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/isBetween/index.js | src/plugin/isBetween/index.js | export default (o, c, d) => {
c.prototype.isBetween = function (a, b, u, i) {
const dA = d(a)
const dB = d(b)
i = i || '()'
const dAi = i[0] === '('
const dBi = i[1] === ')'
return ((dAi ? this.isAfter(dA, u) : !this.isBefore(dA, u)) &&
(dBi ? this.isBefore(dB, u) : !this.isAfter(dB, u)))
|| ((dAi ? this.isBefore(dA, u) : !this.isAfter(dA, u)) &&
(dBi ? this.isAfter(dB, u) : !this.isBefore(dB, u)))
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/toArray/index.js | src/plugin/toArray/index.js | export default (o, c) => {
const proto = c.prototype
proto.toArray = function () {
return [
this.$y,
this.$M,
this.$D,
this.$H,
this.$m,
this.$s,
this.$ms
]
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/arraySupport/index.js | src/plugin/arraySupport/index.js | export default (o, c, dayjs) => {
const proto = c.prototype
const parseDate = (cfg) => {
const { date, utc } = cfg
if (Array.isArray(date)) {
if (utc) {
if (!date.length) {
return new Date()
}
return new Date(Date.UTC.apply(null, date))
}
if (date.length === 1) {
return dayjs(String(date[0])).toDate()
}
return new (Function.prototype.bind.apply(Date, [null].concat(date)))()
}
return date
}
const oldParse = proto.parse
proto.parse = function (cfg) {
cfg.date = parseDate.bind(this)(cfg)
oldParse.bind(this)(cfg)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/localeData/index.js | src/plugin/localeData/index.js | import { t } from '../localizedFormat/utils'
export default (o, c, dayjs) => { // locale needed later
const proto = c.prototype
const getLocalePart = part => (part && (part.indexOf ? part : part.s))
const getShort = (ins, target, full, num, localeOrder) => {
const locale = ins.name ? ins : ins.$locale()
const targetLocale = getLocalePart(locale[target])
const fullLocale = getLocalePart(locale[full])
const result = targetLocale || fullLocale.map(f => f.slice(0, num))
if (!localeOrder) return result
const { weekStart } = locale
return result.map((_, index) => (result[(index + (weekStart || 0)) % 7]))
}
const getDayjsLocaleObject = () => dayjs.Ls[dayjs.locale()]
const getLongDateFormat = (l, format) =>
l.formats[format] || t(l.formats[format.toUpperCase()])
const localeData = function () {
return {
months: instance =>
(instance ? instance.format('MMMM') : getShort(this, 'months')),
monthsShort: instance =>
(instance ? instance.format('MMM') : getShort(this, 'monthsShort', 'months', 3)),
firstDayOfWeek: () => this.$locale().weekStart || 0,
weekdays: instance => (instance ? instance.format('dddd') : getShort(this, 'weekdays')),
weekdaysMin: instance =>
(instance ? instance.format('dd') : getShort(this, 'weekdaysMin', 'weekdays', 2)),
weekdaysShort: instance =>
(instance ? instance.format('ddd') : getShort(this, 'weekdaysShort', 'weekdays', 3)),
longDateFormat: format => getLongDateFormat(this.$locale(), format),
meridiem: this.$locale().meridiem,
ordinal: this.$locale().ordinal
}
}
proto.localeData = function () {
return localeData.bind(this)()
}
dayjs.localeData = () => {
const localeObject = getDayjsLocaleObject()
return {
firstDayOfWeek: () => localeObject.weekStart || 0,
weekdays: () => dayjs.weekdays(),
weekdaysShort: () => dayjs.weekdaysShort(),
weekdaysMin: () => dayjs.weekdaysMin(),
months: () => dayjs.months(),
monthsShort: () => dayjs.monthsShort(),
longDateFormat: format => getLongDateFormat(localeObject, format),
meridiem: localeObject.meridiem,
ordinal: localeObject.ordinal
}
}
dayjs.months = () => getShort(getDayjsLocaleObject(), 'months')
dayjs.monthsShort = () => getShort(getDayjsLocaleObject(), 'monthsShort', 'months', 3)
dayjs.weekdays = localeOrder => getShort(getDayjsLocaleObject(), 'weekdays', null, null, localeOrder)
dayjs.weekdaysShort = localeOrder => getShort(getDayjsLocaleObject(), 'weekdaysShort', 'weekdays', 3, localeOrder)
dayjs.weekdaysMin = localeOrder => getShort(getDayjsLocaleObject(), 'weekdaysMin', 'weekdays', 2, localeOrder)
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/devHelper/index.js | src/plugin/devHelper/index.js | /* eslint-disable no-console */
export default (o, c, d) => {
/* istanbul ignore next line */
if (!process || process.env.NODE_ENV !== 'production') {
const proto = c.prototype
const oldParse = proto.parse
proto.parse = function (cfg) {
const { date } = cfg
if (typeof date === 'string' && date.length === 13) {
console.warn(`To parse a Unix timestamp like ${date}, you should pass it as a Number. https://day.js.org/docs/en/parse/unix-timestamp-milliseconds`)
}
if (typeof date === 'number' && String(date).length === 4) {
console.warn(`Guessing you may want to parse the Year ${date}, you should pass it as a String ${date}, not a Number. Otherwise, ${date} will be treated as a Unix timestamp`)
}
if (cfg.args.length >= 2 && !d.p.customParseFormat) {
console.warn(`To parse a date-time string like ${date} using the given format, you should enable customParseFormat plugin first. https://day.js.org/docs/en/parse/string-format`)
}
return oldParse.bind(this)(cfg)
}
const oldLocale = d.locale
d.locale = function (preset, object, isLocal) {
if (typeof object === 'undefined' && typeof preset === 'string') {
if (!d.Ls[preset]) {
console.warn(`Guessing you may want to use locale ${preset}, you have to load it before using it. https://day.js.org/docs/en/i18n/loading-into-nodejs`)
}
}
return oldLocale(preset, object, isLocal)
}
const oldDiff = proto.diff
proto.diff = function (date, unit, float) {
const isInvalidDate = !date || !d(date).isValid()
if (isInvalidDate) {
console.warn('Invalid usage: diff() requires a valid comparison date as the first argument. https://day.js.org/docs/en/display/difference')
}
return oldDiff.call(this, date, unit, float)
}
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/weekOfYear/index.js | src/plugin/weekOfYear/index.js | import { MS, Y, D, W } from '../../constant'
export default (o, c, d) => {
const proto = c.prototype
proto.week = function (week = null) {
if (week !== null) {
return this.add((week - this.week()) * 7, D)
}
const yearStart = this.$locale().yearStart || 1
if (this.month() === 11 && this.date() > 25) {
// d(this) is for badMutable
const nextYearStartDay = d(this).startOf(Y).add(1, Y).date(yearStart)
const thisEndOfWeek = d(this).endOf(W)
if (nextYearStartDay.isBefore(thisEndOfWeek)) {
return 1
}
}
const yearStartDay = d(this).startOf(Y).date(yearStart)
const yearStartWeek = yearStartDay.startOf(W).subtract(1, MS)
const diffInWeek = this.diff(yearStartWeek, W, true)
if (diffInWeek < 0) {
return d(this).startOf('week').week()
}
return Math.ceil(diffInWeek)
}
proto.weeks = function (week = null) {
return this.week(week)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/dayOfYear/index.js | src/plugin/dayOfYear/index.js | export default (o, c, d) => {
const proto = c.prototype
proto.dayOfYear = function (input) {
// d(this) is for badMutable
const dayOfYear = Math.round((d(this).startOf('day') - d(this).startOf('year')) / 864e5) + 1
return input == null ? dayOfYear : this.add(input - dayOfYear, 'day')
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/isoWeek/index.js | src/plugin/isoWeek/index.js | import { D, W, Y } from '../../constant'
const isoWeekPrettyUnit = 'isoweek'
export default (o, c, d) => {
const getYearFirstThursday = (year, isUtc) => {
const yearFirstDay = (isUtc ? d.utc : d)().year(year).startOf(Y)
let addDiffDays = 4 - yearFirstDay.isoWeekday()
if (yearFirstDay.isoWeekday() > 4) {
addDiffDays += 7
}
return yearFirstDay.add(addDiffDays, D)
}
const getCurrentWeekThursday = ins => ins.add((4 - ins.isoWeekday()), D)
const proto = c.prototype
proto.isoWeekYear = function () {
const nowWeekThursday = getCurrentWeekThursday(this)
return nowWeekThursday.year()
}
proto.isoWeek = function (week) {
if (!this.$utils().u(week)) {
return this.add((week - this.isoWeek()) * 7, D)
}
const nowWeekThursday = getCurrentWeekThursday(this)
const diffWeekThursday = getYearFirstThursday(this.isoWeekYear(), this.$u)
return nowWeekThursday.diff(diffWeekThursday, W) + 1
}
proto.isoWeekday = function (week) {
if (!this.$utils().u(week)) {
return this.day(this.day() % 7 ? week : week - 7)
}
return this.day() || 7
}
const oldStartOf = proto.startOf
proto.startOf = function (units, startOf) {
const utils = this.$utils()
const isStartOf = !utils.u(startOf) ? startOf : true
const unit = utils.p(units)
if (unit === isoWeekPrettyUnit) {
return isStartOf ? this.date(this.date() - (this.isoWeekday() - 1)).startOf('day') :
this.date((this.date() - 1 - (this.isoWeekday() - 1)) + 7).endOf('day')
}
return oldStartOf.bind(this)(units, startOf)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/preParsePostFormat/index.js | src/plugin/preParsePostFormat/index.js | // Plugin template from https://day.js.org/docs/en/plugin/plugin
export default (option, dayjsClass) => {
const oldParse = dayjsClass.prototype.parse
dayjsClass.prototype.parse = function (cfg) {
if (typeof cfg.date === 'string') {
const locale = this.$locale()
cfg.date =
locale && locale.preparse ? locale.preparse(cfg.date) : cfg.date
}
// original parse result
return oldParse.bind(this)(cfg)
}
// // overriding existing API
// // e.g. extend dayjs().format()
const oldFormat = dayjsClass.prototype.format
dayjsClass.prototype.format = function (...args) {
// original format result
const result = oldFormat.call(this, ...args)
// return modified result
const locale = this.$locale()
return locale && locale.postformat ? locale.postformat(result) : result
}
const oldFromTo = dayjsClass.prototype.fromToBase
if (oldFromTo) {
dayjsClass.prototype.fromToBase = function (
input,
withoutSuffix,
instance,
isFrom
) {
const locale = this.$locale() || instance.$locale()
// original format result
return oldFromTo.call(
this,
input,
withoutSuffix,
instance,
isFrom,
locale && locale.postformat
)
}
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/isSameOrAfter/index.js | src/plugin/isSameOrAfter/index.js | export default (o, c) => {
c.prototype.isSameOrAfter = function (that, units) {
return this.isSame(that, units) || this.isAfter(that, units)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/objectSupport/index.js | src/plugin/objectSupport/index.js | export default (o, c, dayjs) => {
const proto = c.prototype
const isObject = obj => obj !== null && !(obj instanceof Date) && !(obj instanceof Array)
&& !proto.$utils().u(obj) && (obj.constructor.name === 'Object')
const prettyUnit = (u) => {
const unit = proto.$utils().p(u)
return unit === 'date' ? 'day' : unit
}
const parseDate = (cfg) => {
const { date, utc } = cfg
const $d = {}
if (isObject(date)) {
if (!Object.keys(date).length) {
return new Date()
}
const now = utc ? dayjs.utc() : dayjs()
Object.keys(date).forEach((k) => {
$d[prettyUnit(k)] = date[k]
})
const d = $d.day || ((!$d.year && !($d.month >= 0)) ? now.date() : 1)
const y = $d.year || now.year()
const M = $d.month >= 0 ? $d.month : ((!$d.year && !$d.day) ? now.month() : 0)// eslint-disable-line no-nested-ternary,max-len
const h = $d.hour || 0
const m = $d.minute || 0
const s = $d.second || 0
const ms = $d.millisecond || 0
if (utc) {
return new Date(Date.UTC(y, M, d, h, m, s, ms))
}
return new Date(y, M, d, h, m, s, ms)
}
return date
}
const oldParse = proto.parse
proto.parse = function (cfg) {
cfg.date = parseDate.bind(this)(cfg)
oldParse.bind(this)(cfg)
}
const oldSet = proto.set
const oldAdd = proto.add
const oldSubtract = proto.subtract
const callObject = function (call, argument, string, offset = 1) {
const keys = Object.keys(argument)
let chain = this
keys.forEach((key) => {
chain = call.bind(chain)(argument[key] * offset, key)
})
return chain
}
proto.set = function (unit, value) {
value = value === undefined ? unit : value
if (unit.constructor.name === 'Object') {
return callObject.bind(this)(function (i, s) {
return oldSet.bind(this)(s, i)
}, value, unit)
}
return oldSet.bind(this)(unit, value)
}
proto.add = function (value, unit) {
if (value.constructor.name === 'Object') {
return callObject.bind(this)(oldAdd, value, unit)
}
return oldAdd.bind(this)(value, unit)
}
proto.subtract = function (value, unit) {
if (value.constructor.name === 'Object') {
return callObject.bind(this)(oldAdd, value, unit, -1)
}
return oldSubtract.bind(this)(value, unit)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/isYesterday/index.js | src/plugin/isYesterday/index.js | export default (o, c, d) => {
const proto = c.prototype
proto.isYesterday = function () {
const comparisonTemplate = 'YYYY-MM-DD'
const yesterday = d().subtract(1, 'day')
return (
this.format(comparisonTemplate) === yesterday.format(comparisonTemplate)
)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/isoWeeksInYear/index.js | src/plugin/isoWeeksInYear/index.js | export default (o, c) => {
const proto = c.prototype
proto.isoWeeksInYear = function () {
const isLeapYear = this.isLeapYear()
const last = this.endOf('y')
const day = last.day()
if (day === 4 || (isLeapYear && day === 5)) {
return 53
}
return 52
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/badMutable/index.js | src/plugin/badMutable/index.js | export default (o, c) => { // locale needed later
const proto = c.prototype
proto.$g = function (input, get, set) {
if (this.$utils().u(input)) return this[get]
return this.$set(set, input)
}
proto.set = function (string, int) {
return this.$set(string, int)
}
const oldStartOf = proto.startOf
proto.startOf = function (units, startOf) {
this.$d = oldStartOf.bind(this)(units, startOf).toDate()
this.init()
return this
}
const oldAdd = proto.add
proto.add = function (number, units) {
this.$d = oldAdd.bind(this)(number, units).toDate()
this.init()
return this
}
const oldLocale = proto.locale
proto.locale = function (preset, object) {
if (!preset) return this.$L
this.$L = oldLocale.bind(this)(preset, object).$L
return this
}
const oldDaysInMonth = proto.daysInMonth
proto.daysInMonth = function () {
return oldDaysInMonth.bind(this.clone())()
}
const oldIsSame = proto.isSame
proto.isSame = function (that, units) {
return oldIsSame.bind(this.clone())(that, units)
}
const oldIsBefore = proto.isBefore
proto.isBefore = function (that, units) {
return oldIsBefore.bind(this.clone())(that, units)
}
const oldIsAfter = proto.isAfter
proto.isAfter = function (that, units) {
return oldIsAfter.bind(this.clone())(that, units)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/minMax/index.js | src/plugin/minMax/index.js | export default (o, c, d) => {
const sortBy = (method, dates) => {
if (
!dates ||
!dates.length ||
(dates.length === 1 && !dates[0]) ||
(dates.length === 1 && Array.isArray(dates[0]) && !dates[0].length)
) {
return null
}
if (dates.length === 1 && dates[0].length > 0) {
[dates] = dates
}
dates = dates.filter(date => date)
let result;
[result] = dates
for (let i = 1; i < dates.length; i += 1) {
if (!dates[i].isValid() || dates[i][method](result)) {
result = dates[i]
}
}
return result
}
d.max = function () {
const args = [].slice.call(arguments, 0) // eslint-disable-line prefer-rest-params
return sortBy('isAfter', args)
}
d.min = function () {
const args = [].slice.call(arguments, 0) // eslint-disable-line prefer-rest-params
return sortBy('isBefore', args)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/customParseFormat/index.js | src/plugin/customParseFormat/index.js | import { u } from '../localizedFormat/utils'
const formattingTokens = /(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g
const match1 = /\d/ // 0 - 9
const match2 = /\d\d/ // 00 - 99
const match3 = /\d{3}/ // 000 - 999
const match4 = /\d{4}/ // 0000 - 9999
const match1to2 = /\d\d?/ // 0 - 99
const matchSigned = /[+-]?\d+/ // -inf - inf
const matchOffset = /[+-]\d\d:?(\d\d)?|Z/ // +00:00 -00:00 +0000 or -0000 +00 or Z
const matchWord = /\d*[^-_:/,()\s\d]+/ // Word
let locale = {}
let parseTwoDigitYear = function (input) {
input = +input
return input + (input > 68 ? 1900 : 2000)
}
function offsetFromString(string) {
if (!string) return 0
if (string === 'Z') return 0
const parts = string.match(/([+-]|\d\d)/g)
const minutes = +(parts[1] * 60) + (+parts[2] || 0)
return minutes === 0 ? 0 : parts[0] === '+' ? -minutes : minutes // eslint-disable-line no-nested-ternary
}
const addInput = function (property) {
return function (input) {
this[property] = +input
}
}
const zoneExpressions = [matchOffset, function (input) {
const zone = this.zone || (this.zone = {})
zone.offset = offsetFromString(input)
}]
const getLocalePart = (name) => {
const part = locale[name]
return part && (
part.indexOf ? part : part.s.concat(part.f)
)
}
const meridiemMatch = (input, isLowerCase) => {
let isAfternoon
const { meridiem } = locale
if (!meridiem) {
isAfternoon = input === (isLowerCase ? 'pm' : 'PM')
} else {
for (let i = 1; i <= 24; i += 1) {
// todo: fix input === meridiem(i, 0, isLowerCase)
if (input.indexOf(meridiem(i, 0, isLowerCase)) > -1) {
isAfternoon = i > 12
break
}
}
}
return isAfternoon
}
const expressions = {
A: [matchWord, function (input) {
this.afternoon = meridiemMatch(input, false)
}],
a: [matchWord, function (input) {
this.afternoon = meridiemMatch(input, true)
}],
Q: [match1, function (input) {
this.month = ((input - 1) * 3) + 1
}],
S: [match1, function (input) {
this.milliseconds = +input * 100
}],
SS: [match2, function (input) {
this.milliseconds = +input * 10
}],
SSS: [match3, function (input) {
this.milliseconds = +input
}],
s: [match1to2, addInput('seconds')],
ss: [match1to2, addInput('seconds')],
m: [match1to2, addInput('minutes')],
mm: [match1to2, addInput('minutes')],
H: [match1to2, addInput('hours')],
h: [match1to2, addInput('hours')],
HH: [match1to2, addInput('hours')],
hh: [match1to2, addInput('hours')],
D: [match1to2, addInput('day')],
DD: [match2, addInput('day')],
Do: [matchWord, function (input) {
const { ordinal } = locale;
[this.day] = input.match(/\d+/)
if (!ordinal) return
for (let i = 1; i <= 31; i += 1) {
if (ordinal(i).replace(/\[|\]/g, '') === input) {
this.day = i
}
}
}],
w: [match1to2, addInput('week')],
ww: [match2, addInput('week')],
M: [match1to2, addInput('month')],
MM: [match2, addInput('month')],
MMM: [matchWord, function (input) {
const months = getLocalePart('months')
const monthsShort = getLocalePart('monthsShort')
const matchIndex = (monthsShort || months.map(_ => _.slice(0, 3))).indexOf(input) + 1
if (matchIndex < 1) {
throw new Error()
}
this.month = (matchIndex % 12) || matchIndex
}],
MMMM: [matchWord, function (input) {
const months = getLocalePart('months')
const matchIndex = months.indexOf(input) + 1
if (matchIndex < 1) {
throw new Error()
}
this.month = (matchIndex % 12) || matchIndex
}],
Y: [matchSigned, addInput('year')],
YY: [match2, function (input) {
this.year = parseTwoDigitYear(input)
}],
YYYY: [match4, addInput('year')],
Z: zoneExpressions,
ZZ: zoneExpressions
}
function correctHours(time) {
const { afternoon } = time
if (afternoon !== undefined) {
const { hours } = time
if (afternoon) {
if (hours < 12) {
time.hours += 12
}
} else if (hours === 12) {
time.hours = 0
}
delete time.afternoon
}
}
function makeParser(format) {
format = u(format, locale && locale.formats)
const array = format.match(formattingTokens)
const { length } = array
for (let i = 0; i < length; i += 1) {
const token = array[i]
const parseTo = expressions[token]
const regex = parseTo && parseTo[0]
const parser = parseTo && parseTo[1]
if (parser) {
array[i] = { regex, parser }
} else {
array[i] = token.replace(/^\[|\]$/g, '')
}
}
return function (input) {
const time = {}
for (let i = 0, start = 0; i < length; i += 1) {
const token = array[i]
if (typeof token === 'string') {
start += token.length
} else {
const { regex, parser } = token
const part = input.slice(start)
const match = regex.exec(part)
const value = match[0]
parser.call(time, value)
input = input.replace(value, '')
}
}
correctHours(time)
return time
}
}
const parseFormattedInput = (input, format, utc, dayjs) => {
try {
if (['x', 'X'].indexOf(format) > -1) return new Date((format === 'X' ? 1000 : 1) * input)
const parser = makeParser(format)
const {
year, month, day, hours, minutes, seconds, milliseconds, zone, week
} = parser(input)
const now = new Date()
const d = day || ((!year && !month) ? now.getDate() : 1)
const y = year || now.getFullYear()
let M = 0
if (!(year && !month)) {
M = month > 0 ? month - 1 : now.getMonth()
}
const h = hours || 0
const m = minutes || 0
const s = seconds || 0
const ms = milliseconds || 0
if (zone) {
return new Date(Date.UTC(y, M, d, h, m, s, ms + (zone.offset * 60 * 1000)))
}
if (utc) {
return new Date(Date.UTC(y, M, d, h, m, s, ms))
}
let newDate
newDate = new Date(y, M, d, h, m, s, ms)
if (week) {
newDate = dayjs(newDate).week(week).toDate()
}
return newDate
} catch (e) {
return new Date('') // Invalid Date
}
}
export default (o, C, d) => {
d.p.customParseFormat = true
if (o && o.parseTwoDigitYear) {
({ parseTwoDigitYear } = o)
}
const proto = C.prototype
const oldParse = proto.parse
proto.parse = function (cfg) {
const {
date,
utc,
args
} = cfg
this.$u = utc
const format = args[1]
if (typeof format === 'string') {
const isStrictWithoutLocale = args[2] === true
const isStrictWithLocale = args[3] === true
const isStrict = isStrictWithoutLocale || isStrictWithLocale
let pl = args[2]
if (isStrictWithLocale) [, , pl] = args
locale = this.$locale()
if (!isStrictWithoutLocale && pl) {
locale = d.Ls[pl]
}
this.$d = parseFormattedInput(date, format, utc, d)
this.init()
if (pl && pl !== true) this.$L = this.locale(pl).$L
// use != to treat
// input number 1410715640579 and format string '1410715640579' equal
// eslint-disable-next-line eqeqeq
if (isStrict && date != this.format(format)) {
this.$d = new Date('')
}
// reset global locale to make parallel unit test
locale = {}
} else if (format instanceof Array) {
const len = format.length
for (let i = 1; i <= len; i += 1) {
args[1] = format[i - 1]
const result = d.apply(this, args)
if (result.isValid()) {
this.$d = result.$d
this.$L = result.$L
this.init()
break
}
if (i === len) this.$d = new Date('')
}
} else {
oldParse.call(this, cfg)
}
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/negativeYear/index.js | src/plugin/negativeYear/index.js | export default (_, c, dayjs) => {
const proto = c.prototype
const parseDate = (cfg) => {
const { date, utc } = cfg
if (typeof date === 'string' && date.charAt(0) === '-') {
const normalData = date.slice(1)
let newDate = dayjs(normalData)
if (utc) {
newDate = dayjs.utc(normalData)
} else {
newDate = dayjs(normalData)
}
const fullYear = newDate.year()
if (date.indexOf(`-${fullYear}`) !== -1) {
return dayjs(newDate).subtract(fullYear * 2, 'year').toDate()
}
return date
}
return date
}
const oldParse = proto.parse
proto.parse = function (cfg) {
cfg.date = parseDate.bind(this)(cfg)
oldParse.bind(this)(cfg)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/duration/index.js | src/plugin/duration/index.js | import {
MILLISECONDS_A_DAY,
MILLISECONDS_A_HOUR,
MILLISECONDS_A_MINUTE,
MILLISECONDS_A_SECOND,
MILLISECONDS_A_WEEK,
REGEX_FORMAT
} from '../../constant'
const MILLISECONDS_A_YEAR = MILLISECONDS_A_DAY * 365
const MILLISECONDS_A_MONTH = MILLISECONDS_A_YEAR / 12
const durationRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/
const unitToMS = {
years: MILLISECONDS_A_YEAR,
months: MILLISECONDS_A_MONTH,
days: MILLISECONDS_A_DAY,
hours: MILLISECONDS_A_HOUR,
minutes: MILLISECONDS_A_MINUTE,
seconds: MILLISECONDS_A_SECOND,
milliseconds: 1,
weeks: MILLISECONDS_A_WEEK
}
const isDuration = d => d instanceof Duration // eslint-disable-line no-use-before-define
let $d
let $u
const wrapper = (input, instance, unit) =>
new Duration(input, unit, instance.$l) // eslint-disable-line no-use-before-define
const prettyUnit = unit => `${$u.p(unit)}s`
const isNegative = number => number < 0
const roundNumber = number =>
(isNegative(number) ? Math.ceil(number) : Math.floor(number))
const absolute = number => Math.abs(number)
const getNumberUnitFormat = (number, unit) => {
if (!number) {
return {
negative: false,
format: ''
}
}
if (isNegative(number)) {
return {
negative: true,
format: `${absolute(number)}${unit}`
}
}
return {
negative: false,
format: `${number}${unit}`
}
}
class Duration {
constructor(input, unit, locale) {
this.$d = {}
this.$l = locale
if (input === undefined) {
this.$ms = 0
this.parseFromMilliseconds()
}
if (unit) {
return wrapper(input * unitToMS[prettyUnit(unit)], this)
}
if (typeof input === 'number') {
this.$ms = input
this.parseFromMilliseconds()
return this
}
if (typeof input === 'object') {
Object.keys(input).forEach((k) => {
this.$d[prettyUnit(k)] = input[k]
})
this.calMilliseconds()
return this
}
if (typeof input === 'string') {
const d = input.match(durationRegex)
if (d) {
const properties = d.slice(2)
const numberD = properties.map(value => (value != null ? Number(value) : 0));
[
this.$d.years,
this.$d.months,
this.$d.weeks,
this.$d.days,
this.$d.hours,
this.$d.minutes,
this.$d.seconds
] = numberD
this.calMilliseconds()
return this
}
}
return this
}
calMilliseconds() {
this.$ms = Object.keys(this.$d).reduce((total, unit) => (
total + ((this.$d[unit] || 0) * (unitToMS[unit]))
), 0)
}
parseFromMilliseconds() {
let { $ms } = this
this.$d.years = roundNumber($ms / MILLISECONDS_A_YEAR)
$ms %= MILLISECONDS_A_YEAR
this.$d.months = roundNumber($ms / MILLISECONDS_A_MONTH)
$ms %= MILLISECONDS_A_MONTH
this.$d.days = roundNumber($ms / MILLISECONDS_A_DAY)
$ms %= MILLISECONDS_A_DAY
this.$d.hours = roundNumber($ms / MILLISECONDS_A_HOUR)
$ms %= MILLISECONDS_A_HOUR
this.$d.minutes = roundNumber($ms / MILLISECONDS_A_MINUTE)
$ms %= MILLISECONDS_A_MINUTE
this.$d.seconds = roundNumber($ms / MILLISECONDS_A_SECOND)
$ms %= MILLISECONDS_A_SECOND
this.$d.milliseconds = $ms
}
toISOString() {
const Y = getNumberUnitFormat(this.$d.years, 'Y')
const M = getNumberUnitFormat(this.$d.months, 'M')
let days = +this.$d.days || 0
if (this.$d.weeks) {
days += this.$d.weeks * 7
}
const D = getNumberUnitFormat(days, 'D')
const H = getNumberUnitFormat(this.$d.hours, 'H')
const m = getNumberUnitFormat(this.$d.minutes, 'M')
let seconds = this.$d.seconds || 0
if (this.$d.milliseconds) {
seconds += this.$d.milliseconds / 1000
seconds = Math.round(seconds * 1000) / 1000
}
const S = getNumberUnitFormat(seconds, 'S')
const negativeMode =
Y.negative ||
M.negative ||
D.negative ||
H.negative ||
m.negative ||
S.negative
const T = H.format || m.format || S.format ? 'T' : ''
const P = negativeMode ? '-' : ''
const result = `${P}P${Y.format}${M.format}${D.format}${T}${H.format}${m.format}${S.format}`
return result === 'P' || result === '-P' ? 'P0D' : result
}
toJSON() {
return this.toISOString()
}
format(formatStr) {
const str = formatStr || 'YYYY-MM-DDTHH:mm:ss'
const matches = {
Y: this.$d.years,
YY: $u.s(this.$d.years, 2, '0'),
YYYY: $u.s(this.$d.years, 4, '0'),
M: this.$d.months,
MM: $u.s(this.$d.months, 2, '0'),
D: this.$d.days,
DD: $u.s(this.$d.days, 2, '0'),
H: this.$d.hours,
HH: $u.s(this.$d.hours, 2, '0'),
m: this.$d.minutes,
mm: $u.s(this.$d.minutes, 2, '0'),
s: this.$d.seconds,
ss: $u.s(this.$d.seconds, 2, '0'),
SSS: $u.s(this.$d.milliseconds, 3, '0')
}
return str.replace(REGEX_FORMAT, (match, $1) => $1 || String(matches[match]))
}
as(unit) {
return this.$ms / (unitToMS[prettyUnit(unit)])
}
get(unit) {
let base = this.$ms
const pUnit = prettyUnit(unit)
if (pUnit === 'milliseconds') {
base %= 1000
} else if (pUnit === 'weeks') {
base = roundNumber(base / unitToMS[pUnit])
} else {
base = this.$d[pUnit]
}
return base || 0 // a === 0 will be true on both 0 and -0
}
add(input, unit, isSubtract) {
let another
if (unit) {
another = input * unitToMS[prettyUnit(unit)]
} else if (isDuration(input)) {
another = input.$ms
} else {
another = wrapper(input, this).$ms
}
return wrapper(this.$ms + (another * (isSubtract ? -1 : 1)), this)
}
subtract(input, unit) {
return this.add(input, unit, true)
}
locale(l) {
const that = this.clone()
that.$l = l
return that
}
clone() {
return wrapper(this.$ms, this)
}
humanize(withSuffix) {
return $d()
.add(this.$ms, 'ms')
.locale(this.$l)
.fromNow(!withSuffix)
}
valueOf() {
return this.asMilliseconds()
}
milliseconds() { return this.get('milliseconds') }
asMilliseconds() { return this.as('milliseconds') }
seconds() { return this.get('seconds') }
asSeconds() { return this.as('seconds') }
minutes() { return this.get('minutes') }
asMinutes() { return this.as('minutes') }
hours() { return this.get('hours') }
asHours() { return this.as('hours') }
days() { return this.get('days') }
asDays() { return this.as('days') }
weeks() { return this.get('weeks') }
asWeeks() { return this.as('weeks') }
months() { return this.get('months') }
asMonths() { return this.as('months') }
years() { return this.get('years') }
asYears() { return this.as('years') }
}
const manipulateDuration = (date, duration, k) =>
date.add(duration.years() * k, 'y')
.add(duration.months() * k, 'M')
.add(duration.days() * k, 'd')
.add(duration.hours() * k, 'h')
.add(duration.minutes() * k, 'm')
.add(duration.seconds() * k, 's')
.add(duration.milliseconds() * k, 'ms')
export default (option, Dayjs, dayjs) => {
$d = dayjs
$u = dayjs().$utils()
dayjs.duration = function (input, unit) {
const $l = dayjs.locale()
return wrapper(input, { $l }, unit)
}
dayjs.isDuration = isDuration
const oldAdd = Dayjs.prototype.add
const oldSubtract = Dayjs.prototype.subtract
Dayjs.prototype.add = function (value, unit) {
if (isDuration(value)) {
return manipulateDuration(this, value, 1)
}
return oldAdd.bind(this)(value, unit)
}
Dayjs.prototype.subtract = function (value, unit) {
if (isDuration(value)) {
return manipulateDuration(this, value, -1)
}
return oldSubtract.bind(this)(value, unit)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/isToday/index.js | src/plugin/isToday/index.js | export default (o, c, d) => {
const proto = c.prototype
proto.isToday = function () {
const comparisonTemplate = 'YYYY-MM-DD'
const now = d()
return this.format(comparisonTemplate) === now.format(comparisonTemplate)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/toObject/index.js | src/plugin/toObject/index.js | export default (o, c) => {
const proto = c.prototype
proto.toObject = function () {
return {
years: this.$y,
months: this.$M,
date: this.$D,
hours: this.$H,
minutes: this.$m,
seconds: this.$s,
milliseconds: this.$ms
}
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/quarterOfYear/index.js | src/plugin/quarterOfYear/index.js | import { Q, M, D } from '../../constant'
export default (o, c) => {
const proto = c.prototype
proto.quarter = function (quarter) {
if (!this.$utils().u(quarter)) {
return this.month((this.month() % 3) + ((quarter - 1) * 3))
}
return Math.ceil((this.month() + 1) / 3)
}
const oldAdd = proto.add
proto.add = function (number, units) {
number = Number(number) // eslint-disable-line no-param-reassign
const unit = this.$utils().p(units)
if (unit === Q) {
return this.add(number * 3, M)
}
return oldAdd.bind(this)(number, units)
}
const oldStartOf = proto.startOf
proto.startOf = function (units, startOf) {
const utils = this.$utils()
const isStartOf = !utils.u(startOf) ? startOf : true
const unit = utils.p(units)
if (unit === Q) {
const quarter = this.quarter() - 1
return isStartOf ? this.month(quarter * 3)
.startOf(M).startOf(D) :
this.month((quarter * 3) + 2).endOf(M).endOf(D)
}
return oldStartOf.bind(this)(units, startOf)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/weekYear/index.js | src/plugin/weekYear/index.js | export default (o, c) => {
const proto = c.prototype
proto.weekYear = function () {
const month = this.month()
const weekOfYear = this.week()
const year = this.year()
if (weekOfYear === 1 && month === 11) {
return year + 1
}
if (month === 0 && weekOfYear >= 52) {
return year - 1
}
return year
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/isSameOrBefore/index.js | src/plugin/isSameOrBefore/index.js | export default (o, c) => {
c.prototype.isSameOrBefore = function (that, units) {
return this.isSame(that, units) || this.isBefore(that, units)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
iamkun/dayjs | https://github.com/iamkun/dayjs/blob/54f447048cee679e51a7053f8042d9b6b7028b89/src/plugin/isMoment/index.js | src/plugin/isMoment/index.js | export default (o, c, f) => {
f.isMoment = function (input) {
return f.isDayjs(input)
}
}
| javascript | MIT | 54f447048cee679e51a7053f8042d9b6b7028b89 | 2026-01-04T14:57:31.496629Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.