initial import

This commit is contained in:
2020-12-23 10:11:11 +01:00
commit be83b43a59
5600 changed files with 577973 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
describe("Accessibility Tests", function() {
var sliderA;
var sliderB;
it("Should have the slider role", function() {
sliderA = $('#accessibilitySliderA').slider();
sliderB = $('#accessibilitySliderB').slider();
var $sliderElementA = $(sliderA.slider('getElement'));
var $sliderElementB = $(sliderB.slider('getElement'));
expect($sliderElementA.find('.min-slider-handle').attr('role')).toBe('slider');
expect($sliderElementB.find('.min-slider-handle').attr('role')).toBe('slider');
expect($sliderElementB.find('.max-slider-handle').attr('role')).toBe('slider');
expect($sliderElementA.find('.tooltip-main').attr('role')).toBe('presentation');
expect($sliderElementA.find('.tooltip-min').attr('role')).toBe('presentation');
expect($sliderElementA.find('.tooltip-max').attr('role')).toBe('presentation');
});
it('Should have an aria-labelledby attribute', function() {
sliderA = $('#accessibilitySliderA').slider();
sliderB = $('#accessibilitySliderB').slider();
expect($(sliderA.slider('getElement')).find('.min-slider-handle').attr('aria-labelledby')).toBe('accessibilitySliderLabelA');
expect($(sliderB.slider('getElement')).find('.min-slider-handle').attr('aria-labelledby')).toBe('accessibilitySliderLabelA');
expect($(sliderB.slider('getElement')).find('.max-slider-handle').attr('aria-labelledby')).toBe('accessibilitySliderLabelB');
});
it('Should have an aria-valuemax and aria-valuemin value', function() {
sliderA = $('#accessibilitySliderA').slider({ min: 5, max: 10 });
sliderB = $('#accessibilitySliderB').slider({ min: 5, max: 10 });
var $sliderElementA = $(sliderA.slider('getElement'));
var $sliderElementB = $(sliderB.slider('getElement'));
expect($sliderElementA.find('.min-slider-handle').attr('aria-valuemin')).toBe('5');
expect($sliderElementA.find('.min-slider-handle').attr('aria-valuemax')).toBe('10');
expect($sliderElementB.find('.min-slider-handle').attr('aria-valuemin')).toBe('5');
expect($sliderElementB.find('.min-slider-handle').attr('aria-valuemax')).toBe('10');
expect($sliderElementB.find('.max-slider-handle').attr('aria-valuemin')).toBe('5');
expect($sliderElementB.find('.max-slider-handle').attr('aria-valuemax')).toBe('10');
});
it('Should have an aria-valuenow with the current value', function() {
sliderA = $('#accessibilitySliderA').slider({ min: 5, value: 7 });
sliderB = $('#accessibilitySliderB').slider({ min: 5, value: [2, 8] });
var $sliderElementA = $(sliderA.slider('getElement'));
var $sliderElementB = $(sliderB.slider('getElement'));
expect($sliderElementA.find('.min-slider-handle').attr('aria-valuenow')).toBe('7');
expect($sliderElementB.find('.min-slider-handle').attr('aria-valuenow')).toBe('5');
expect($sliderElementB.find('.max-slider-handle').attr('aria-valuenow')).toBe('8');
// Change the value and check if aria-valuenow is still the same
sliderA.slider('setValue', 1);
sliderB.slider('setValue', [4, 9]);
expect($sliderElementA.find('.min-slider-handle').attr('aria-valuenow')).toBe('5');
expect($sliderElementB.find('.min-slider-handle').attr('aria-valuenow')).toBe('5');
expect($sliderElementB.find('.max-slider-handle').attr('aria-valuenow')).toBe('9');
});
afterEach(function() {
if(sliderA) { sliderA.slider('destroy'); }
if(sliderB) { sliderB.slider('destroy'); }
});
});

View File

@@ -0,0 +1,114 @@
describe("Aria-valuetext Tests", function() {
it("Sets the aria-valuetext to 'formatter' value", function() {
var textValArrayA = new Array('Monday','Wednesday','Friday');
var tooltipFormatterA = function(value) {
var arrActiveValueA = value;
return textValArrayA[arrActiveValueA-1];
};
//Formatter is used
var testSliderA = $("#accessibilitySliderA").slider({
formatter : tooltipFormatterA
});
testSliderA.slider('setValue', 2);
var tooltipMessageA = $("#accessibilitySliderA").prev(".slider").children(".min-slider-handle").attr("aria-valuetext");
var expectedMessageA = tooltipFormatterA(2);
expect(tooltipMessageA).toBe(expectedMessageA);
$("#accessibilitySliderA").slider('destroy');
});
it("Does not use aria-valuetext if 'formatter' is not used", function() {
//Formatter is not used
var testSliderB = $("#accessibilitySliderB").slider({});
testSliderB.slider('setValue', 1);
var ariaValueTextB = $("#accessibilitySliderB").prev(".slider").children(".min-slider-handle").attr("aria-valuetext");
expect(ariaValueTextB).not.toBeDefined();
$("#accessibilitySliderB").slider('destroy');
});
it("aria-valuetext if 'formatter' is used and has min & max value", function() {
var textValArrayC = new Array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
var tooltipFormatterC = function(value) {
if(value[1]){
var arrActiveValueC0 = value[0];
var arrActiveValueC1 = value[1];
return [ textValArrayC[arrActiveValueC0-1], textValArrayC[arrActiveValueC1-1] ];
} else {
var arrActiveValueC = value;
return textValArrayC[arrActiveValueC-1];
}
};
//Formatter is used for ranges
var testSliderC = $("#accessibilitySliderC").slider({
range: true,
formatter : tooltipFormatterC
});
var valuesToSet = [2,4];
testSliderC.slider('setValue', valuesToSet);
var expectedMessageC = tooltipFormatterC([2,4]);
var ttminMessage = $("#accessibilitySliderC").prev(".slider").children(".min-slider-handle").attr("aria-valuetext");
var ttmaxMessage = $("#accessibilitySliderC").prev(".slider").children(".max-slider-handle").attr("aria-valuetext");
expect(ttminMessage).toBe(expectedMessageC[0]);
expect(ttmaxMessage).toBe(expectedMessageC[1]);
$('#accessibilitySliderC').slider('destroy');
});
describe("Unset 'aria-valuetext' attribute when value can be represented as a number", function() {
var $testSliderC;
var dayOfWeek;
var dayFormatter = function(value) {
if (value[1]) {
return [ dayOfWeek[value[0]-1], dayOfWeek[value[1]-1] ];
}
return dayOfWeek[value-1];
};
beforeEach(function() {
dayOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
$testSliderC = $('#accessibilitySliderC').slider({
id: 'testAccessbilitySlider',
min: 1,
max: 7,
formatter : dayFormatter
});
});
afterEach(function() {
if ($testSliderC) {
$testSliderC.slider('destroy');
}
});
it("Should unset 'aria-valuetext' attribute", function() {
dayOfWeek[0] = '1';
var valueToSet = 1;
$testSliderC.slider('setValue', valueToSet);
var ariaValueText = $('#testAccessbilitySlider').find('.min-slider-handle')[0].getAttribute('aria-valuetext');
expect(ariaValueText).toBeNull();
});
it("Should unset 'aria-valuetext' attributes for range sliders", function() {
dayOfWeek[0] = '1';
dayOfWeek[6] = '7';
$testSliderC.slider('setAttribute', 'range', true);
$testSliderC.slider('refresh');
var valuesToSet = [1, 7];
$testSliderC.slider('setValue', valuesToSet);
var ariaValueText1 = $('#testAccessbilitySlider').find('.min-slider-handle')[0].getAttribute('aria-valuetext');
var ariaValueText2 = $('#testAccessbilitySlider').find('.max-slider-handle')[0].getAttribute('aria-valuetext');
expect(ariaValueText1).toBeNull();
expect(ariaValueText2).toBeNull();
});
});
});

View File

@@ -0,0 +1,21 @@
describe("Auto register data-provide Tests", function() {
it("checks that the autoregister Slider was automatically registerd", function() {
var $el = $("#autoregisterSlider");
var sliderInstancesExists = $el.siblings().is(".slider");
expect(sliderInstancesExists).toBeTruthy();
var sliderInstancesCount = $el.siblings(".slider").length;
expect(sliderInstancesCount).toEqual(1);
});
it("checks that the autoregistered Slider can be accessed", function() {
var $el = $("#autoregisterSlider");
expect($el.slider('getValue')).toBe(1);
$el.slider('setValue', 2);
expect($el.slider('getValue')).toBe(2);
});
});

View File

@@ -0,0 +1,73 @@
/*
*************************
Conflicting Options Tests
*************************
This spec has tests for checking if two or more options do not conflict with one another
As option conflicts are reported and resolved, write tests for them here.
This will help ensure that they are accounted for and do not arise again.
*/
describe("Conflicting Options Tests", function() {
var testSlider;
it("Should have the value zero when it is slided to zero", function() {
testSlider = $("#testSlider1").slider({
value: 0,
step: 1
});
var flag = false;
var mouse = document.createEvent('MouseEvents');
testSlider.on('slide', function(slideEvt) {
expect(slideEvt.value).toBe(0);
flag = true;
});
testSlider.data('slider')._mousemove(mouse);
expect(flag).toBeTruthy();
});
it("should set the `precision` to be the number of digits after the decimal of the `step` (assuming no `precision` is specified)", function() {
// Create Slider
testSlider = $("#testSlider1").slider({
value: 8.115,
step: 0.01
});
// Retrieve slider value
var value = testSlider.slider("getValue");
// Run tests
expect(value).toBe(8.12);
});
it("should properly allow for a slider that has `range` set to true and `reversed` set to true", function() {
// Create Slider
testSlider = new Slider("#testSlider1", {
reversed: true,
range: true,
min: -5,
max: 20
});
// Set Value
testSlider.setValue([-5, 20]);
// Assert that selection slider section is 100% of slider width
var selectedSectionWidth = testSlider.sliderElem.querySelector(".slider-selection").style.width;
expect(selectedSectionWidth).toBe("100%");
// Cleanup
testSlider.destroy();
testSlider = null;
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});

View File

@@ -0,0 +1,416 @@
describe("'destroy()' Method tests", function() {
var testSlider;
function createSliderFn() {
testSlider = new Slider("#testSlider1", {
id: "destroyMethodTestSlider"
});
}
it("removes the extra DOM elements associated with a slider", function() {
createSliderFn();
testSlider.destroy();
var sliderParentElement = $("#testSlider1").parent('div.slider').length;
var sliderChildrenElements = $("#testSlider1").siblings('div.slider-track, div.tooltip').length;
expect(sliderParentElement).toBe(0);
expect(sliderChildrenElements).toBe(0);
});
describe("Destroy slider instance associated with <input> element", function() {
var sourceJS = "temp/bootstrap-slider.js";
var defaultNamespace = 'slider';
var alternateNamespace = 'bootstrapSlider';
it("Should remove the instance associated with the <input> DOM element", function() {
var $testSlider = $('#testSlider1').slider();
var sliderInst = $testSlider.data(defaultNamespace);
expect(sliderInst).toBeTruthy();
$testSlider.slider('destroy');
sliderInst = $testSlider.data(defaultNamespace);
expect(sliderInst).toBeUndefined();
});
describe("Check alternate namespace", function() {
afterEach(function(done) {
$.fn.bootstrapSlider = undefined;
$.fn.slider = undefined;
$.getScript(sourceJS, function() {
done();
});
});
it("Should remove the instance associated with the <input> DOM element with alternate namespace", function(done) {
$.fn.slider = function() {};
$.getScript(sourceJS, function() {
var $testSlider = $('#testSlider1').bootstrapSlider();
$testSlider.bootstrapSlider('destroy');
var sliderInst = $testSlider.data(alternateNamespace);
expect(sliderInst).toBeUndefined();
done();
});
});
});
});
describe("unbinds all slider events", function() {
var flag, evtName;
beforeEach(function() {
createSliderFn();
flag = false;
});
it("unbinds from 'slideStart' event", function() {
evtName = 'slideStart';
$("#destroyMethodTestSlider").on(evtName, function() {
flag = true;
});
testSlider.destroy();
$("#destroyMethodTestSlider").trigger(evtName);
expect(flag).toBeFalsy();
});
it("unbinds from 'slide' event", function() {
evtName = 'slide';
$("#destroyMethodTestSlider").on(evtName, function() {
flag = true;
});
testSlider.destroy();
$("#destroyMethodTestSlider").trigger(evtName);
expect(flag).toBeFalsy();
});
it("unbinds from 'slideStop' event", function() {
evtName = 'slideStop';
$("#destroyMethodTestSlider").on(evtName, function() {
flag = true;
});
testSlider.destroy();
$("#destroyMethodTestSlider").trigger(evtName);
expect(flag).toBeFalsy();
});
it("unbinds from 'slideChange' event", function() {
evtName = 'slideChange';
$("#destroyMethodTestSlider").on(evtName, function() {
flag = true;
});
testSlider.destroy();
$("#destroyMethodTestSlider").trigger(evtName);
expect(flag).toBeFalsy();
});
it("unbinds all slider events and allows you to re-create the slider without runtime error", function() {
// Setup
var createSliderAndBindEvent = function () {
$("#testSlider1").bootstrapSlider({
min: 0,
max: 1000 * 1000,
step: 1000
});
testSlider = $("#testSlider1").data("bootstrapSlider");
testSlider.on("slideStop", function() {});
};
// Destroy existing slider from default bootstrap step
testSlider.destroy();
// Create new Slider
createSliderAndBindEvent();
// Destroy slider
testSlider.destroy();
// Re-create Slider and try to re-bind event
var throwsRuntimeError = false;
try {
createSliderAndBindEvent();
}
catch (e) {
throwsRuntimeError = true;
}
testSlider.destroy();
// reCreateSliderAndBindEvent(): Assert error is not thrown
expect(throwsRuntimeError).toBeFalsy();
});
});
describe("DOM event listener removal tests", function() {
describe("When tooltips are always hidden for single value sliders", function() {
beforeEach(function() {
// Create slider
testSlider = new Slider("#testSlider1", {
id: "destroyMethodTestSlider",
tooltip: "hide"
});
});
it("does not try to remove 'focus' event listener from handle1", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("focus", undefined, false);
});
it("does not try to remove 'blur' event listener from handle1", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("blur", undefined, false);
});
it("does not try to remove 'mouseenter' event listener from slider", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.sliderElem, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.sliderElem.removeEventListener).not.toHaveBeenCalledWith("mouseenter", undefined, false);
});
it("does not try to remove 'mouseleave' event listener from slider", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.sliderElem, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.sliderElem.removeEventListener).not.toHaveBeenCalledWith("mouseleave", undefined, false);
});
});
describe("When tooltips are always shown for single value sliders", function() {
beforeEach(function() {
// Create slider
testSlider = new Slider("#testSlider1", {
id: "destroyMethodTestSlider",
tooltip: "always"
});
});
it("does not try to remove 'focus' event listener from handle1 when tooltip is always shown for single handle sliders", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("focus", undefined, false);
});
it("does not try to remove 'blur' event listener from handle1 when tooltip is always shown for single handle sliders", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("blur", undefined, false);
});
it("does not try to remove 'mouseenter' event listener from slider is always shown for single handle slider", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("mouseenter", undefined, false);
});
it("does not try to remove 'mouseleave' event listener from slider is always shown for single handle slider", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.sliderElem, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.sliderElem.removeEventListener).not.toHaveBeenCalledWith("mouseleave", undefined, false);
});
});
describe("When tooltips are always hidden for range sliders", function() {
beforeEach(function() {
// Create slider
testSlider = new Slider("#testSlider1", {
id: "destroyMethodTestSlider",
tooltip: "always",
value: [2,5]
});
});
it("does not try to remove 'focus' event listener from handle1", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("focus", undefined, false);
});
it("does not try to remove 'focus' event listener from handle2", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle2, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle2.removeEventListener).not.toHaveBeenCalledWith("focus", undefined, false);
});
it("does not try to remove 'blur' event listener from handle1", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("blur", undefined, false);
});
it("does not try to remove 'blur' event listener from handle2", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle2, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle2.removeEventListener).not.toHaveBeenCalledWith("blur", undefined, false);
});
it("does not try to remove 'mouseenter' event listener from slider", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.sliderElem, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.sliderElem.removeEventListener).not.toHaveBeenCalledWith("mouseenter", undefined, false);
});
it("does not try to remove 'mouseleave' event listener from slider", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.sliderElem, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.sliderElem.removeEventListener).not.toHaveBeenCalledWith("mouseleave", undefined, false);
});
});
describe("When tooltips are always shown for range sliders", function() {
beforeEach(function() {
// Create slider
testSlider = new Slider("#testSlider1", {
id: "destroyMethodTestSlider",
tooltip: "always",
value: [2,5]
});
});
it("does not try to remove 'focus' event listener from handle1", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("focus", undefined, false);
});
it("does not try to remove 'focus' event listener from handle2", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle2, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle2.removeEventListener).not.toHaveBeenCalledWith("focus", undefined, false);
});
it("does not try to remove 'blur' event listener from handle1", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle1, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle1.removeEventListener).not.toHaveBeenCalledWith("blur", undefined, false);
});
it("does not try to remove 'blur' event listener from handle1 and handle2", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.handle2, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.handle2.removeEventListener).not.toHaveBeenCalledWith("blur", undefined, false);
});
it("does not try to remove 'mouseenter' event listener from slider", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.sliderElem, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.sliderElem.removeEventListener).not.toHaveBeenCalledWith("mouseenter", undefined, false);
});
it("does not try to remove 'mouseleave' event listener from slider", function() {
// Set up spy on 'removeEventListener'
spyOn(testSlider.sliderElem, "removeEventListener");
// Destroy slider
testSlider.destroy();
// Assert
expect(testSlider.sliderElem.removeEventListener).not.toHaveBeenCalledWith("mouseleave", undefined, false);
});
});
});
});

View File

@@ -0,0 +1,293 @@
describe("Dragging handles tests", function() {
var testSlider;
var mouseEventArguments;
var tickOffsets;
// Create mouse events
function mouseEvent(type, offset) {
var ev = document.createEvent("MouseEvents");
mouseEventArguments[0] = type;
mouseEventArguments[7] = offset;
ev.initMouseEvent.apply(ev, mouseEventArguments);
return ev;
}
beforeEach(function() {
// Create slider
testSlider = new Slider(document.getElementById("testSlider1"), {
ticks: [0, 1, 2, 3, 4, 5, 6],
value: [4, 5],
step: 1,
range: true,
});
// Set up default set of mouse event arguments
mouseEventArguments = [
'mousemove', // type
true, // canBubble
true, // cancelable
document, // view,
0, // detail
0, // screenX
0, // screenY
undefined, // clientX
testSlider.sliderElem.offsetTop, // clientY,
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey,
0, // button
null // relatedTarget
];
// Calculate and store the 'clientX' for each tick in the slider
tickOffsets = testSlider.ticks.map(function (tick) {
return tick.offsetLeft + testSlider.sliderElem.offsetLeft;
});
});
afterEach(function() {
if(testSlider) {
if(testSlider instanceof Slider) { testSlider.destroy(); }
testSlider = null;
}
});
describe("Dragging handles over each other", function() {
it("should swap reliably given imprecision", function() {
// Create mouse event with position to the left of problem tick
var mouseLeft = document.createEvent('MouseEvents');
mouseEventArguments[7] = tickOffsets[4]; // clientX
mouseLeft.initMouseEvent.apply(mouseLeft, mouseEventArguments);
// Create mouse event with position on problem tick
var mouseOverlap = document.createEvent('MouseEvents');
mouseEventArguments[7] = tickOffsets[5]; // clientX
mouseOverlap.initMouseEvent.apply(mouseOverlap, mouseEventArguments);
// Create mouse event with position to the right of problem tick
var mouseRight = document.createEvent('MouseEvents');
mouseEventArguments[7] = tickOffsets[6]; // clientX
mouseRight.initMouseEvent.apply(mouseRight, mouseEventArguments);
// Same offset as 'mouseLeft'
var mouseUp = document.createEvent('MouseEvents');
mouseEventArguments[7] = testSlider.ticks[4].offsetLeft + testSlider.sliderElem.offsetLeft; // clientX
mouseUp.initMouseEvent.apply(mouseUp, mouseEventArguments);
// Simulate drag without swapping
testSlider.mousedown(mouseLeft);
expect(testSlider._state.dragged).toBe(0);
expect(testSlider.getValue()).toEqual([4, 5]);
// Simulate handle overlap
testSlider.mousemove(mouseOverlap);
expect(testSlider._state.dragged).toBe(0);
expect(testSlider.getValue()).toEqual([5, 5]);
// Simulate left over right drag with imprecision in reported percentage
testSlider.mousemove(mouseRight);
expect(testSlider._state.dragged).toBe(1);
expect(testSlider.getValue()).toEqual([5, 6]);
// Simulate handle overlap
testSlider.mousemove(mouseOverlap);
expect(testSlider._state.dragged).toBe(1);
expect(testSlider.getValue()).toEqual([5, 5]);
// Simulator handle overlap with click
testSlider.mousemove(mouseOverlap);
testSlider.mousedown(mouseLeft);
expect(testSlider._state.dragged).toBe(0);
expect(testSlider.getValue()).toEqual([4, 5]);
// Simulate right over left drag with imprecision in reported percentage
testSlider.mousemove(mouseLeft);
expect(testSlider._state.dragged).toBe(0);
expect(testSlider.getValue()).toEqual([4, 5]);
// End with mouse up
testSlider.mouseup(mouseUp);
expect(testSlider._state.dragged).toBeNull();
expect(testSlider.getValue()).toEqual([4, 5]);
});
});
describe("Drag handles over each other and use keyboard to move handles over each other", function() {
var keyboardEvent;
function createMouseEvent(type, tickIdx) {
var mouseEvent = document.createEvent('MouseEvent');
mouseEventArguments[0] = type;
mouseEventArguments[7] = tickOffsets[tickIdx];
mouseEvent.initMouseEvent.apply(mouseEvent, mouseEventArguments);
return mouseEvent;
}
beforeEach(function() {
// Create keyboard event
keyboardEvent = document.createEvent('Event');
keyboardEvent.initEvent('keydown', true, true);
});
afterEach(function() {
keyboardEvent = null;
});
it("should drag and keydown handles properly to the right then back to the left", function() {
// Simulate drag without swapping
testSlider.mousedown(createMouseEvent('mousedown', 4));
expect(testSlider._state.dragged).toBe(0);
expect(testSlider.getValue()).toEqual([4, 5]);
// Simulate handle overlap
testSlider.mousemove(createMouseEvent('mousemove', 5));
expect(testSlider._state.dragged).toBe(0);
expect(testSlider.getValue()).toEqual([5, 5]);
// Simulate left over right drag
testSlider.mousemove(createMouseEvent('mousemove', 6));
expect(testSlider._state.dragged).toBe(1);
expect(testSlider.getValue()).toEqual([5, 6]);
// End with mouse up
testSlider.mouseup(createMouseEvent('mouseup', 6));
expect(testSlider._state.dragged).toBeNull();
expect(testSlider.getValue()).toEqual([5, 6]);
// Now move the handles past each other with the Left arrow key
keyboardEvent.keyCode = keyboardEvent.which = 37;
// Move handle2 to the left with keyboard
testSlider.handle2Keydown(keyboardEvent);
expect(testSlider._state.keyCtrl).toBeUndefined();
expect(testSlider.getValue()).toEqual([5, 5]);
// Move handle2 to the left again
testSlider.handle2Keydown(keyboardEvent);
expect(testSlider._state.keyCtrl).toBeUndefined();
expect(testSlider.getValue()).toEqual([4, 5]);
});
it("should drag and keydown handles properly to the left then back to the right", function() {
// Simulate drag without swapping
testSlider.mousedown(createMouseEvent('mousedown', 5));
expect(testSlider._state.dragged).toBe(1);
expect(testSlider.getValue()).toEqual([4, 5]);
// Simulate handle overlap
testSlider.mousemove(createMouseEvent('mousemove', 4));
expect(testSlider._state.dragged).toBe(1);
expect(testSlider.getValue()).toEqual([4, 4]);
// Simulate left over right drag
testSlider.mousemove(createMouseEvent('mousemove', 3));
expect(testSlider._state.dragged).toBe(0);
expect(testSlider.getValue()).toEqual([3, 4]);
// End with mouse up
testSlider.mouseup(createMouseEvent('mouseup', 3));
expect(testSlider._state.dragged).toBeNull();
expect(testSlider.getValue()).toEqual([3, 4]);
// Now move the handles past each other with the Right arrow key
keyboardEvent.keyCode = keyboardEvent.which = 39;
// Move handle1 to the right with keyboard
testSlider.handle1Keydown(keyboardEvent);
expect(testSlider._state.keyCtrl).toBeUndefined();
expect(testSlider.getValue()).toEqual([4, 4]);
// Move handle1 to the right again
testSlider.handle1Keydown(keyboardEvent);
expect(testSlider._state.keyCtrl).toBeUndefined();
expect(testSlider.getValue()).toEqual([4, 5]);
});
});
it("Should snap to a tick within tick bounds when using the mouse navigation", function() {
testSlider.setAttribute('range', true);
testSlider.setAttribute('ticks_snap_bounds', 0.45);
testSlider.setAttribute('step', 0.1);
testSlider.refresh();
// Create mouse events
var mouseDown = document.createEvent("MouseEvents");
mouseEventArguments[7] = tickOffsets[1];
mouseDown.initMouseEvent.apply(mouseDown, mouseEventArguments);
var mouseRight = document.createEvent("MouseEvents");
mouseEventArguments[7] = tickOffsets[2] - 2;
mouseRight.initMouseEvent.apply(mouseRight, mouseEventArguments);
testSlider.mousedown(mouseDown);
expect(testSlider.getValue()).toEqual([0.7, 5]);
testSlider.mousemove(mouseRight);
expect(testSlider.getValue()).toEqual([2, 5]);
// FIXME: Use 'mouseup' event type
// End with mouse up
testSlider.mouseup(mouseRight);
expect(testSlider.getValue()).toEqual([2, 5]);
});
it("Should trigger change on mouseup", function(done) {
var changes = 0;
testSlider.on('slideStop', function(){
expect(changes).toBe(1);
expect(testSlider.getValue()).toEqual([2, 5]);
done();
});
testSlider.mousedown(mouseEvent('mousedown', tickOffsets[1]));
expect(testSlider.getValue()).toEqual([1, 5]);
testSlider.on('change', function(){
changes++;
});
testSlider.mouseup(mouseEvent('mouseup', tickOffsets[2]));
});
describe("Test 'mousemove' and 'mouseup' produces correct results", function() {
var $mySlider;
var $handle1;
function arraysEqual(a, b) {
if (a === b) { return true; }
if (a == null || b == null) { return false; }
if (a.length !== b.length) { return false; }
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) { return false; }
}
return true;
}
it("Last value changed in 'change' event should equal 'mouseup' event value for slider", function(done) {
// Change attributes for 'testSlider'
testSlider.setAttribute('value', 3);
testSlider.setAttribute('range', false);
testSlider.refresh();
$mySlider = $('#testSlider1');
function createMouseEvent(type, tickIdx) {
var mouseEvent = document.createEvent('MouseEvent');
mouseEventArguments[0] = type;
mouseEventArguments[7] = tickOffsets[tickIdx];
mouseEvent.initMouseEvent.apply(mouseEvent, mouseEventArguments);
return mouseEvent;
}
var lastValue = 99; // Dummy value
$mySlider.on('change', function(eventData) {
lastValue = eventData.value.newValue;
});
$mySlider.on('slideStop', function(eventData) {
var value = eventData.value;
var isEqual = Array.isArray(value) ? arraysEqual(lastValue, value) : value === lastValue;
expect(isEqual).toBe(true);
done();
});
// Simulate drag and release from tick[1] to tick[4]
$handle1 = testSlider.$sliderElem.find('.slider-handle:first');
$handle1[0].dispatchEvent(createMouseEvent('mousedown', 1));
$handle1[0].dispatchEvent(createMouseEvent('mousemove', 4));
$handle1[0].dispatchEvent(createMouseEvent('mouseup', 4));
});
});
});

View File

@@ -0,0 +1,211 @@
describe("Element Data Attributes Tests", function() {
var slider;
it("reads the 'data-slider-min' property and sets it on slider", function() {
slider = $("#minSlider").slider();
slider.slider('setValue', 1);
var sliderValue = slider.slider('getValue');
expect(sliderValue).toBe(5);
});
it("reads the 'data-slider-max' property and sets it on slider", function() {
slider = $("#maxSlider").slider();
slider.slider('setValue', 10);
var sliderValue = slider.slider('getValue');
expect(sliderValue).toBe(5);
});
it("reads the 'data-slider-step' property and sets it on slider", function() {
slider = $("#stepSlider").slider();
//TODO How do you test this? Maybe manually trigger a slideChange event?
expect(true).toBeTruthy();
});
it("reads the 'data-slider-precision' property (which is set to 2) and sets it on slider", function() {
slider = $("#precisionSlider").slider();
slider.slider('setValue', 8.115);
var sliderValue = slider.slider('getValue');
expect(sliderValue).toBe(8.12);
});
it("reads the 'data-slider-orientation' property and sets it on slider", function() {
slider = $("#orientationSlider").slider();
var orientationIsVertical = $("#orientationSlider").data('slider').options.orientation === 'vertical';
expect(orientationIsVertical).toBeTruthy();
});
it("reads the 'data-slider-value' property and sets it on slider", function() {
slider = $("#valueSlider").slider();
var sliderValue = slider.slider('getValue');
expect(sliderValue).toBe(5);
});
it("reads the 'data-slider-ticks-labels' property and sets it on slider", function() {
slider = $("#sliderWithTickMarksAndLabels").slider();
var ticksLabelsAreCorrect = arraysEqual($("#sliderWithTickMarksAndLabels").data('slider').options.ticks_labels, ['$0', '$100', '$200', '$300', '$400']);
expect(ticksLabelsAreCorrect).toBeTruthy();
function arraysEqual(a, b) {
if (a === b) {return true;}
if (a == null || b == null){return false;}
if (a.length !== b.length) {return false;}
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) {return false;}
}
return true;
}
});
it("reads the 'data-slider-selection' property and sets it on slider", function() {
slider = $("#selectionSlider").slider({
id: "selectionSliderId"
});
slider.slider('setValue', 0);
var newSliderValue = slider.slider('getValue');
expect(newSliderValue).toBe(0);
});
it("reads the 'data-slider-tooltip' property and sets it on slider", function() {
slider = $("#tooltipSlider").slider({
id: "tooltipSliderElem"
});
var tooltipIsHidden = $("#tooltipSliderElem").children("div.tooltip").hasClass("hide");
expect(tooltipIsHidden).toBeTruthy();
});
describe("reads the 'data-slider-handle' property and sets it on slider", function() {
it("applies 'triangle' class tag to handle", function() {
slider = $("#handleSlider").slider({
id: "handleSliderElem"
});
var handleIsSetToTriangle = $("#handleSliderElem div.slider-handle").hasClass("triangle");
expect(handleIsSetToTriangle).toBeTruthy();
});
it("applies 'custom' class tag to handle", function() {
slider = $("#customHandleSlider").slider({
id: "customHandleSliderElem"
});
var handleIsSetToCustom = $("#customHandleSliderElem div.slider-handle").hasClass("custom");
expect(handleIsSetToCustom).toBeTruthy();
});
});
it("reads the 'data-slider-reversed' property and sets it on slider", function() {
slider = $("#reversedSlider").slider({
id: "reversedSliderElem"
});
slider.slider('setValue', 10);
var sliderSelectionHeightAtMaxValue = $("#reversedSliderElem div.slider-track").children("div.slider-selection").width();
expect(sliderSelectionHeightAtMaxValue).toBe(0);
});
it("reads the 'data-slider-enabled' property and sets it on slider", function() {
slider = $("#disabledSlider").slider();
var isEnabled = slider.slider('isEnabled');
expect(isEnabled).not.toBeTruthy();
});
it("always sets the 'value' attribute of the original <input> element to be the current slider value", function() {
var $slider = $("#testSliderGeneric");
var val = 7;
slider = $slider.slider({
value: val
});
var sliderValueAttrib = $slider.val();
var valAsString = val.toString();
expect(sliderValueAttrib).toBe(valAsString);
});
it("always sets the 'data-value' attribute of the original <input> element to be the current slider value", function() {
// Setup
var sliderInputElem = document.getElementById("testSliderGeneric");
var val = 7;
slider = new Slider(sliderInputElem, {
value: val
});
// Assert
expect(sliderInputElem.dataset.value).toBe( val.toString() );
// Cleanup
slider.destroy();
slider = null;
});
afterEach(function() {
if(slider) { slider.slider('destroy'); }
});
describe("Test element attribute values after calling 'setValue()'", function() {
var sliderObj;
afterEach(function() {
if (sliderObj) {
sliderObj.destroy();
sliderObj = null;
}
});
it("The 'data-value' attribute of the original <input> element should equal the new value", function() {
// Setup
var sliderInputElem = document.getElementById("testSliderGeneric");
var newVal = 7;
sliderObj = new Slider(sliderInputElem, {
min: 0,
max: 10,
value: 5
});
sliderObj.setValue(newVal);
expect(sliderInputElem.dataset.value).toBe(newVal.toString());
});
it("The 'value' attribute of the original <input> element should equal the new value", function() {
var sliderInputElem = document.getElementById("testSliderGeneric");
var newVal = 7;
sliderObj = new Slider(sliderInputElem, {
min: 0,
max: 10,
value: 5
});
sliderObj.setValue(newVal);
var sliderValueAttrib = sliderInputElem.getAttribute('value');
expect(sliderValueAttrib).toBe(newVal.toString());
});
it("The 'value' property of the original <input> element should equal the new value", function() {
var sliderInputElem = document.getElementById("testSliderGeneric");
var newVal = 7;
sliderObj = new Slider(sliderInputElem, {
min: 0,
max: 10,
value: 5
});
sliderObj.setValue(newVal);
expect(sliderInputElem.value).toBe(newVal.toString());
});
});
});

View File

@@ -0,0 +1,493 @@
describe("Event Tests", function() {
var testSlider, flag, mouse;
var sliderElem;
beforeEach(function() {
flag = false;
mouse = document.createEvent('MouseEvents');
});
describe("JQuery version", function() {
beforeEach(function() {
testSlider = $("#testSlider2").slider({
value: 1
});
sliderElem = testSlider.slider('getElement');
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
sliderElem = null;
});
describe("Mouse Events", function() {
var spy;
beforeEach(function() {
spy = jasmine.createSpy('spy');
});
it("'slideStart' event is triggered properly and can be binded to", function(done) {
testSlider.on('slideStart', spy);
testSlider.data('slider')._mousedown(mouse);
setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
});
it("'slide' event is triggered properly and can be binded to", function(done) {
testSlider.on('slide', spy);
testSlider.data('slider')._mousemove(mouse);
setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
});
it("'slide' event sets the right value on the input", function(done) {
testSlider.on('slide', function() {
expect(isNaN(testSlider.val())).not.toBeTruthy();
done();
});
testSlider.data('slider')._mousemove(mouse);
});
it("'slide' event value and input value properties are synchronous", function() {
testSlider.on('slide', function(e) {
expect(e.value.toString()).toEqual(this.value);
});
testSlider.slider("setValue", 3, true, false);
});
it("'change' event value and input value properties are synchronous", function() {
testSlider.on('change', function(e) {
expect(e.value.newValue.toString()).toEqual(testSlider.val());
});
testSlider.slider("setValue", 3, false, true);
});
it("'slideStop' event is triggered properly and can be binded to", function(done) {
testSlider.on('slideStop', spy);
testSlider.data('slider')._mouseup(mouse);
setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
});
it("slider should not have duplicate events after calling 'refresh'", function(done) {
var numTimesFired = 0;
var obj = {
addOne: function() {
numTimesFired++;
}
};
spyOn(obj, 'addOne').and.callThrough();
testSlider.on('slideStop', obj.addOne);
testSlider.slider('refresh');
testSlider.data('slider')._mouseup(mouse);
setTimeout(function() {
expect(numTimesFired).toBe(1);
expect(obj.addOne.calls.count()).toBe(1);
done();
});
});
describe("Disabled Slider Event Tests", function() {
var spy;
beforeEach(function() {
testSlider.slider('disable');
spy = jasmine.createSpy('spy');
});
it("should not trigger 'slideStart' event when disabled", function(done) {
testSlider.on('slideStart', spy);
testSlider.data('slider')._mousedown(mouse);
window.setTimeout(function() {
expect(spy).not.toHaveBeenCalled();
done();
});
});
it("should not trigger 'slide' event when disabled", function(done) {
testSlider.on('slide', spy);
testSlider.data('slider')._mousemove(mouse);
window.setTimeout(function() {
expect(spy).not.toHaveBeenCalled();
done();
});
});
it("should not trigger 'slideStop' event when disabled", function(done) {
testSlider.on('slideStop', spy);
testSlider.data('slider')._mouseup(mouse);
window.setTimeout(function() {
expect(spy).not.toHaveBeenCalled();
done();
});
});
});
});
describe("Touch Events", function() {
var touch;
var spy;
var coords;
var touchStart;
var touchMove;
var touchEnd;
/*
list can be either [[x, y], [x, y]] or [x, y]
*/
function createTouchList(target, list) {
if (Array.isArray(list) && list[0] && !Array.isArray(list[0])) {
list = [list];
}
list = list.map(function (entry, index) {
var x = entry[0], y = entry[1], id = entry[2] ? entry[2] : index + 1;
return createTouch(x, y, target, id);
});
return document.createTouchList.apply(document, list);
}
function createTouch(x, y, target, id) {
return document.createTouch(window, target,
id || 1, //identifier
x, //pageX / clientX
y, //pageY / clientY
x, //screenX
y //screenY
);
}
function initTouchEvent(touchEvent, type, touches) {
var touch1 = touches[0];
return touchEvent.initTouchEvent(
touches, //touches
touches, //targetTouches
touches, //changedTouches
type, //type
window, //view
touch1.screenX, //screenX
touch1.screenY, //screenY
touch1.clientX, //clientX
touch1.clientY, //clientY
false, //ctrlKey
false, //altKey
false, //shiftKey
false //metaKey
);
}
function createTouchEvent(elem, type, touches) {
var touchEvent = document.createEvent('TouchEvent');
if (Array.isArray(touches)) {
touches = createTouchList(elem, touches);
}
initTouchEvent(touchEvent, type, touches);
return touchEvent;
}
function calcTouchEventCoords(element) {
var elementBB = element.getBoundingClientRect();
return {
clientX: elementBB.left,
clientY: elementBB.top
};
}
beforeEach(function() {
touch = document.createEvent('Event');
var dummyTouchEvent = document.createEvent('MouseEvents');
touch.touches = [dummyTouchEvent];
window.ontouchstart = true;
spy = jasmine.createSpy('spy');
coords = calcTouchEventCoords(sliderElem);
touchStart = createTouchEvent(sliderElem, 'touchstart', [coords.clientX, coords.clientY]);
touchMove = createTouchEvent(sliderElem, 'touchmove', [coords.clientX, coords.clientY]);
touchEnd = createTouchEvent(sliderElem, 'touchend', [[0, 0]]);
});
afterEach(function() {
window.ontouchstart = null;
});
it("'slideStart' event is triggered properly and can be binded to", function(done) {
testSlider.on('slideStart', spy);
window.setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchEnd);
});
it("'slide' event is triggered properly and can be binded to", function(done) {
testSlider.on('slide', spy);
window.setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
// Expect to fail if ONLY dispatching 'touchmove' because `preventDefault()` will prevent
// the browser from sending the corresponding 'mousemove'.
// The 'mousedown' event must happen first via 'touchstart'.
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
// Always call 'touchend' to remove any touch event listeners on the document.
sliderElem.dispatchEvent(touchEnd);
});
it("'slide' event sets the right value on the input", function(done) {
testSlider.on('slide', function() {
expect(isNaN(testSlider.val())).not.toBeTruthy();
done();
});
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
it("'slide' event value and input value properties are synchronous", function() {
testSlider.on('slide', function(e) {
expect(e.value.toString()).toEqual(testSlider.val());
});
testSlider.slider("setValue", 3, true, false);
});
it("'change' event value and input value properties are synchronous", function() {
testSlider.on('change', function(e) {
expect(e.value.newValue.toString()).toEqual(testSlider.val());
});
testSlider.slider("setValue", 3, false, true);
});
it("'slideStop' event is triggered properly and can be binded to", function(done) {
testSlider.on('slideStop', spy);
window.setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
it("slider should not have duplicate events after calling 'refresh'", function(done) {
// FIXME: Should set `flag` to 0 and make sure spy is called only once
testSlider.on('slideStop', spy);
window.setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
testSlider.slider('refresh');
});
it("slider should not bind multiple touchstart events after calling 'refresh'", function(done) {
flag = 0;
var obj = {
addOne: function() {
flag++;
}
};
spyOn(obj, 'addOne').and.callThrough();
touch.initEvent("touchstart", true, true);
testSlider.on('slideStart', obj.addOne);
var handleElem = $('#testSlider2').prev('div.slider').find('.slider-handle:first').get(0);
handleElem.dispatchEvent(touchStart);
handleElem.dispatchEvent(touchMove);
handleElem.dispatchEvent(touchEnd);
testSlider.slider('refresh');
window.setTimeout(function() {
expect(flag).toBe(1);
expect(obj.addOne.calls.count()).toBe(1);
done();
});
});
describe("Disabled Slider Event Tests", function() {
var spy;
beforeEach(function() {
testSlider.slider('disable');
spy = jasmine.createSpy('spy');
});
it("should not trigger 'slideStart' event when disabled", function(done) {
touch.initEvent("touchstart");
testSlider.on('slideStart', spy);
testSlider.data('slider')._mousedown(touch);
window.setTimeout(function() {
expect(spy).not.toHaveBeenCalled();
done();
});
});
it("should not trigger 'slide' event when disabled", function(done) {
touch.initEvent("touchmove");
testSlider.on('slide', spy);
testSlider.data('slider')._mousemove(touch);
window.setTimeout(function() {
expect(spy).not.toHaveBeenCalled();
done();
});
});
it("should not trigger 'slideStop' event when disabled", function(done) {
touch.initEvent("touchend");
testSlider.on('slideStop', spy);
testSlider.data('slider')._mouseup(mouse);
window.setTimeout(function() {
expect(spy).not.toHaveBeenCalled();
done();
});
});
});
});
describe("Enabled/Disabled tests", function() {
var spy;
beforeEach(function() {
spy = jasmine.createSpy('spy');
});
it("'slideDisabled' event is triggered properly and can be binded to", function(done) {
testSlider.on('slideDisabled', spy);
testSlider.slider('disable');
window.setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
});
it("'slideDisabled' event is triggered properly and can be binded to", function(done) {
testSlider.on('slideEnabled', spy);
testSlider.slider('disable');
testSlider.slider('enable');
window.setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
});
it("'change' event is triggered properly and can be binded to", function(done) {
testSlider.on('change', spy);
testSlider.slider("setValue", 3, false, true);
window.setTimeout(function() {
expect(spy).toHaveBeenCalled();
done();
});
});
});
}); // End of JQuery version tests
describe("CommonJS version", function() {
describe("Event repetition tests", function() {
var testSlider, numTimesFired;
var testObj;
beforeEach(function() {
testSlider = new Slider("#testSlider2");
numTimesFired = 0;
testObj = {
addOne: function() {
numTimesFired++;
}
};
});
afterEach(function() {
testSlider.destroy();
});
it("'slide' event is triggered only once per slide action", function(done) {
spyOn(testObj, 'addOne').and.callThrough();
testSlider.on('slide', testObj.addOne);
testSlider._mousemove(mouse);
setTimeout(function() {
expect(numTimesFired).toBe(1);
expect(testObj.addOne.calls.count()).toBe(1);
done();
});
});
it("'slideStart' event is triggered only once per slide action", function(done) {
spyOn(testObj, 'addOne').and.callThrough();
testSlider.on('slideStart', testObj.addOne);
testSlider._mousedown(mouse);
setTimeout(function() {
expect(numTimesFired).toBe(1);
expect(testObj.addOne.calls.count()).toBe(1);
done();
});
});
it("'slideStop' event is triggered only once per slide action", function(done) {
spyOn(testObj, 'addOne').and.callThrough();
testSlider.on('slideStop', testObj.addOne);
testSlider._mouseup(mouse);
setTimeout(function() {
expect(numTimesFired).toBe(1);
expect(testObj.addOne.calls.count()).toBe(1);
done();
});
});
it("'change' event is triggered only once per value change action", function(done) {
spyOn(testObj, 'addOne').and.callThrough();
testSlider.on('change', testObj.addOne);
testSlider.setValue(3, false, true);
setTimeout(function() {
expect(numTimesFired).toBe(1);
expect(testObj.addOne.calls.count()).toBe(1);
done();
});
});
});
}); // End of common JS tests
}); // End of spec

View File

@@ -0,0 +1,67 @@
/*
******************
Focus Option Tests
******************
This spec has tests for checking proper behavior of the focus option.
*/
describe("Focus Option Tests", function() {
var testSlider;
var simulateMousedown = function(target, pos) {
var myEvent = document.createEvent("MouseEvents");
myEvent.initEvent("mousedown", true, true);
myEvent.pageX = pos;
myEvent.pageY = pos;
target.dispatchEvent(myEvent);
};
it("handle should not be focused after value change when 'focus' is false", function() {
testSlider = $("#testSlider1").slider({
min : 0,
max : 10,
value: 0,
focus: false,
id : "testSlider"
});
var hasFocus;
$("#testSlider").find(".min-slider-handle").focus(function() {
hasFocus = true;
});
simulateMousedown($("#testSlider").find(".slider-track-high").get(0), 1000);
expect(hasFocus).toBe(undefined);
});
it("handle should be focused after value change when 'focus' is true", function() {
testSlider = $("#testSlider1").slider({
min : 0,
max : 10,
value: 0,
focus: true,
id : "testSlider"
});
var hasFocus;
$("#testSlider").find(".min-slider-handle").focus(function() {
hasFocus = true;
});
simulateMousedown($("#testSlider").find(".slider-track-high").get(0), 1000);
expect(hasFocus).toBe(true);
});
afterEach(function() {
if (testSlider) {
testSlider.slider("destroy");
testSlider = null;
}
});
});

View File

@@ -0,0 +1,768 @@
describe("Keyboard Support Tests", function() {
var testSlider,
handle1,
handle2,
keyboardEvent,
initialMinVal = 0,
initialMaxVal = 10,
initialStepVal = 1,
initialSliderVal = 5;
/*
Before/After setup
*/
beforeEach(function() {
// Create keyboard event
keyboardEvent = document.createEvent("Events");
keyboardEvent.initEvent("keydown", true, true);
});
afterEach(function() {
if(testSlider) { testSlider.slider('destroy'); }
keyboardEvent = null;
keyboardEvent = null;
});
/*
Begin Tests
*/
describe("Clicking on slider handle automatically gives it focus", function() {
beforeEach(function() {
testSlider = $("#testSlider1").slider({
id: 'testSlider'
});
handle1 = $("#testSlider").find(".slider-handle:first");
});
it("clicking on handle1 gives focus to handle1", function(done) {
handle1.focus(function() {
expect(true).toBeTruthy();
done();
});
handle1.focus();
});
});
describe("When slider handle has TAB focus", function() {
it("should display it's tooltip if 'tooltip' option is set to 'show'", function() {
testSlider = $("#testSlider1").slider({
id: 'testSlider',
tooltip: 'show'
});
handle1 = $("#testSlider").find(".slider-handle:first");
// Check for no tooltip before focus
var tooltipIsShown = $("#testSlider").find("div.tooltip").hasClass("in");
expect(tooltipIsShown).toBeFalsy();
handle1.focus();
// Tooltip should be present after focus
tooltipIsShown = $("#testSlider").find("div.tooltip").hasClass("in");
expect(tooltipIsShown).toBeTruthy();
});
it("should not display it's tooltip if 'tooltip' option is set to 'hide'", function() {
testSlider = $("#testSlider1").slider({
id: 'testSlider',
tooltip: 'hide'
});
handle1 = $("#testSlider").find(".slider-handle:first");
// Check for hidden tooltip before focus
var tooltipIsHidden = $("#testSlider").children("div.tooltip").hasClass("hide");
expect(tooltipIsHidden).toBeTruthy();
handle1.focus();
// Tooltip should remain hidden after focus
tooltipIsHidden = $("#testSlider").children("div.tooltip").hasClass("hide");
expect(tooltipIsHidden).toBeTruthy();
});
it("should not affect the tooltip display if 'tooltip' option is set to 'always'", function() {
testSlider = $("#testSlider1").slider({
id: 'testSlider',
tooltip: 'always'
});
handle1 = $("#testSlider").find(".slider-handle:first");
var $tooltip = $("#testSlider").children("div.tooltip");
// Check for shown tooltip before focus
var tooltipIsShown = $tooltip.hasClass("in");
expect(tooltipIsShown).toBeTruthy();
handle1.focus();
// Tooltip should remain present after focus
tooltipIsShown = $tooltip.hasClass("in");
expect(tooltipIsShown).toBeTruthy();
});
});
describe("For horizontal sliders where its handle has focus", function() {
beforeEach(function() {
// Initialize the slider
testSlider = $("#testSlider1").slider({
id: 'testSlider',
orientation: 'horizontal',
min: initialMinVal,
max: initialMaxVal,
step: initialStepVal,
value: initialSliderVal
});
// Focus on handle1
handle1 = $("#testSlider .min-slider-handle");
handle1.focus();
});
it("moves to the left by the 'step' value when the LEFT arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = $("#testSlider1").slider('getValue');
var expectedSliderValue = initialSliderVal - initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 37;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves to the right by the 'step' value when the RIGHT arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = $("#testSlider1").slider('getValue');
var expectedSliderValue = initialSliderVal + initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 39;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves to the left by the 'step' value when the DOWN arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal - initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 40;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves to the right by the 'step' value when the UP arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal + initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 38;
handle1[0].dispatchEvent(keyboardEvent);
});
});
describe("For vertical sliders where its handle has focus", function() {
beforeEach(function() {
// Initialize the slider
testSlider = $("#testSlider1").slider({
id: 'testSlider',
orientation: 'vertical',
min: initialMinVal,
max: initialMaxVal,
step: initialStepVal,
value: initialSliderVal
});
// Focus on handle1
handle1 = $("#testSlider").find(".slider-handle:first");
handle1.focus();
});
it("moves down by the 'step' value when the LEFT arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal - initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 37;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves up by the 'step' value when the RIGHT arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal + initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 39;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves down by the 'step' value when the DOWN arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal - initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 40;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves up by the 'step' value when the UP arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal + initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 38;
handle1[0].dispatchEvent(keyboardEvent);
});
});
describe("For a reversed slider (regardless of 'orientation')", function() {
beforeEach(function() {
// Initialize the slider
testSlider = $("#testSlider1").slider({
id: 'testSlider',
reversed: true,
min: initialMinVal,
max: initialMaxVal,
step: initialStepVal,
value: initialSliderVal
});
// Focus on handle1
handle1 = $("#testSlider").find(".slider-handle:first");
handle1.focus();
});
it("moves to the left by the 'step' value when the LEFT arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal - initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 37;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves to the right by the 'step' value when the RIGHT arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal + initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 39;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves to the left by the 'step' value when the DOWN arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal - initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 40;
handle1[0].dispatchEvent(keyboardEvent);
});
it("moves to the right by the 'step' value when the UP arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal + initialStepVal;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 38;
handle1[0].dispatchEvent(keyboardEvent);
});
});
describe("For a range slider (regardless of 'orientation')", function() {
beforeEach(function() {
// Initialize the slider
testSlider = $("#testSlider1").slider({
id: 'testSlider',
min: initialMinVal,
max: initialMaxVal,
step: initialStepVal,
value: [initialSliderVal, initialSliderVal]
});
});
describe("when handle1 tries to overtake handle2 from the left", function() {
beforeEach(function() {
handle1 = $("#testSlider").find(".slider-handle:first");
handle2 = $("#testSlider").find(".slider-handle:last");
handle1.focus();
});
it("handle2 moves to the right by the step value", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal + initialStepVal;
expect(sliderValue[1]).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 39;
handle1[0].dispatchEvent(keyboardEvent);
});
it("handle1's value remains unchanged", function(done) {
var sliderValue = testSlider.slider('getValue');
handle1.on("keydown", function() {
expect(sliderValue[0]).toBe(initialSliderVal);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 39;
handle1[0].dispatchEvent(keyboardEvent);
});
it("Should give focus to handle2 after overtaking from the left", function(done) {
handle2.on("focus", function() {
expect(true).toBe(true);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 39;
handle1[0].dispatchEvent(keyboardEvent);
});
});
describe("when handle2 tries to overtake handle1 from the right", function() {
beforeEach(function() {
handle1 = $("#testSlider").find(".slider-handle:first");
handle2 = $("#testSlider").find(".slider-handle:last");
handle2.focus();
});
it("handle1 moves to the left by the step value", function(done) {
handle2.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = initialSliderVal - initialStepVal;
expect(sliderValue[0]).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 37;
handle2[0].dispatchEvent(keyboardEvent);
});
it("handle2's value remains unchanged", function(done) {
var sliderValue = testSlider.slider('getValue');
handle2.on("keydown", function() {
expect(sliderValue[1]).toBe(initialSliderVal);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 37;
handle2[0].dispatchEvent(keyboardEvent);
});
it("Should give focus to handle1 after overtaking from the right", function(done) {
handle1.on("focus", function() {
expect(true).toBe(true);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = 37;
handle2[0].dispatchEvent(keyboardEvent);
});
});
});
describe("For the natural arrow keys", function() {
var testCases = [{
reversed: false,
keyEvent: 37,
expectedSliderValue: initialSliderVal - initialStepVal,
orientation: 'horizontal',
key: 'left'
}, {
reversed: true,
keyEvent: 37,
expectedSliderValue: initialSliderVal + initialStepVal,
orientation: 'horizontal',
key: 'left'
}, {
reversed: false,
keyEvent: 39,
expectedSliderValue: initialSliderVal + initialStepVal,
orientation: 'horizontal',
key: 'right'
}, {
reversed: true,
keyEvent: 39,
expectedSliderValue: initialSliderVal - initialStepVal,
orientation: 'horizontal',
key: 'right'
}, {
reversed: false,
keyEvent: 38,
expectedSliderValue: initialSliderVal - initialStepVal,
orientation: 'vertical',
key: 'up'
}, {
reversed: true,
keyEvent: 38,
expectedSliderValue: initialSliderVal + initialStepVal,
orientation: 'vertical',
key: 'up'
}, {
reversed: false,
keyEvent: 40,
expectedSliderValue: initialSliderVal + initialStepVal,
orientation: 'vertical',
key: 'down'
}, {
reversed: true,
keyEvent: 40,
expectedSliderValue: initialSliderVal - initialStepVal,
orientation: 'vertical',
key: 'down'
}];
testCases.forEach(function(testCase) {
describe("A"+((testCase.reversed)? " reversed" : "")+testCase.orientation+" slider is used for the arrow keys", function() {
beforeEach(function() {
// Initialize the slider
testSlider = $("#testSlider1").slider({
id: 'testSlider',
min: initialMinVal,
max: initialMaxVal,
step: initialStepVal,
value: initialSliderVal,
natural_arrow_keys: true,
reversed: testCase.reversed,
orientation: testCase.orientation
});
handle1 = $("#testSlider").find(".slider-handle:first");
handle1.focus();
});
it("moves to the "+testCase.key+" by the 'step' value when the "+testCase.key+" arrow key is pressed", function(done) {
handle1.on("keydown", function() {
var sliderValue = testSlider.slider('getValue');
var expectedSliderValue = testCase.expectedSliderValue;
expect(sliderValue).toBe(expectedSliderValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = testCase.keyEvent;
handle1[0].dispatchEvent(keyboardEvent);
});
});
});
});
});
describe("Navigating slider with the keyboard", function() {
var mySlider;
var keyboardEvent;
var options;
var $handle1;
var $handle2;
describe("Does not trigger 'change' event when values do not change", function() {
var initialValues = [0, 1];
beforeEach(function() {
options = {
id: 'mySlider',
min: -100,
max: 100,
step: 1,
value: initialValues,
range: true
};
// Create keyboard event
keyboardEvent = document.createEvent('Event');
keyboardEvent.initEvent('keydown', true, true);
});
afterEach(function() {
if (mySlider) {
if (mySlider instanceof Slider) { mySlider.destroy(); }
mySlider = null;
}
});
it("Should not trigger 'change' event", function(done) {
var hasSlideStarted = false;
var hasChanged = false;
options.value = [-100, 0];
mySlider = new Slider($('#testSlider1')[0], options);
$handle1 = $('#mySlider').find('.slider-handle:first');
mySlider.on('slideStart', function() {
hasSlideStarted = true;
});
mySlider.on('change', function() {
hasChanged = true;
});
mySlider.on('slideStop', function() {
var value = mySlider.getValue();
expect(hasSlideStarted).toBe(true);
expect(hasChanged).toBe(false);
expect(value).toEqual([-100, 0]);
done();
});
// Move the handle to the left
keyboardEvent.keyCode = keyboardEvent.which = 37;
$handle1[0].dispatchEvent(keyboardEvent);
});
it("Should not trigger 'change' event via `setValue()`", function(done) {
var isSliding = false;
var hasChanged = false;
mySlider = new Slider($('#testSlider1')[0], options);
$handle1 = $('#mySlider').find('.slider-handle:first');
mySlider.on('slide', function() {
isSliding = true;
});
mySlider.on('change', function() {
hasChanged = true;
});
// Change both values of the range slider
mySlider.setValue(initialValues, true, true);
window.setTimeout(function() {
var value = mySlider.getValue();
expect(isSliding).toBe(true);
expect(hasChanged).toBe(false);
expect(value).toEqual(initialValues);
done();
});
});
});
describe("Does trigger 'change' event when either value changes for range sliders", function() {
beforeEach(function() {
options = {
id: 'mySlider',
min: -100,
max: 100,
step: 1,
value: [-10, 10],
range: true
};
// Create keyboard event
keyboardEvent = document.createEvent('Event');
keyboardEvent.initEvent('keydown', true, true);
});
afterEach(function() {
if (mySlider) {
if (mySlider instanceof Slider) { mySlider.destroy(); }
mySlider = null;
}
});
it("Should trigger 'change' event when the moving the lower handle", function(done) {
var hasSlideStarted = false;
var hasChanged = false;
mySlider = new Slider($('#testSlider1')[0], options);
$handle1 = $('#mySlider').find('.slider-handle:first');
mySlider.on('slideStart', function() {
hasSlideStarted = true;
});
mySlider.on('change', function() {
hasChanged = true;
});
mySlider.on('slideStop', function() {
var value = mySlider.getValue();
expect(hasSlideStarted).toBe(true);
expect(hasChanged).toBe(true);
expect(value).toEqual([-11, 10]);
done();
});
// Move the handle to the left
keyboardEvent.keyCode = keyboardEvent.which = 37;
$handle1[0].dispatchEvent(keyboardEvent);
});
it("Should trigger 'change' event when moving the upper handle", function(done) {
var hasSlideStarted = false;
var hasChanged = false;
mySlider = new Slider($('#testSlider1')[0], options);
$handle2 = $('#mySlider').find('.slider-handle:last');
mySlider.on('slideStart', function() {
hasSlideStarted = true;
});
mySlider.on('change', function() {
hasChanged = true;
});
mySlider.on('slideStop', function() {
var value = mySlider.getValue();
expect(hasSlideStarted).toBe(true);
expect(hasChanged).toBe(true);
expect(value).toEqual([-10, 11]);
done();
});
// Move the handle to the right
keyboardEvent.keyCode = keyboardEvent.which = 39;
$handle2[0].dispatchEvent(keyboardEvent);
});
it("Should trigger 'change' event when both values change via `setValue()`", function(done) {
var isSliding = false;
mySlider = new Slider($('#testSlider1')[0], options);
$handle2 = $('#mySlider').find('.slider-handle:last');
mySlider.on('slide', function() {
isSliding = true;
});
mySlider.on('change', function() {
var value = mySlider.getValue();
expect(isSliding).toBe(true);
expect(value).toEqual([-50, 50]);
done();
});
// Change both values of the range slider
mySlider.setValue([-50, 50], true, true);
});
});
});
describe("Navigating range sliders with the keyboard", function() {
var mySlider;
var keyboardEvent;
var options;
var $handle1;
var $handle2;
describe("Range slider values", function() {
beforeEach(function() {
options = {
id: 'mySlider',
min: -100,
max: 100,
step: 1,
value: [0, 1],
range: true
};
// Create keyboard event
keyboardEvent = document.createEvent('Event');
keyboardEvent.initEvent('keydown', true, true);
});
afterEach(function() {
if (mySlider) {
if (mySlider instanceof Slider) { mySlider.destroy(); }
mySlider = null;
}
});
it("Should not go below minimum at 'slideStart'", function(done) {
options.value = [-100, 0];
mySlider = new Slider($('#testSlider1')[0], options);
$handle1 = $('#mySlider').find('.slider-handle:first');
mySlider.on('slideStart', function(newVal) {
expect(newVal).toEqual([-100, 0]);
done();
});
// Move the handle to the left
keyboardEvent.keyCode = keyboardEvent.which = 37;
$handle1[0].dispatchEvent(keyboardEvent);
});
it("Should not go above maximum at 'slideStart'", function(done) {
options.value = [0, 100];
mySlider = new Slider($('#testSlider1')[0], options);
$handle2 = $('#mySlider').find('.slider-handle:last');
mySlider.on('slideStart', function(newVal) {
expect(newVal).toEqual([0, 100]);
done();
});
// Move the handle to the right
keyboardEvent.keyCode = keyboardEvent.which = 39;
$handle2[0].dispatchEvent(keyboardEvent);
});
});
});

View File

@@ -0,0 +1,699 @@
/*
*************************
Lock To Ticks Tests
*************************
Verify that the when lock_to_ticks is true, the selected values will be snapped to closest tick values
*/
describe("Slider with lock_to_ticks: true tests", function() {
var testSlider;
it("Should set `options.lock_to_ticks` to false when `ticks[]` is not set", function() {
testSlider = $('#testSlider1').slider({
lock_to_ticks: true
});
var lockAttr = testSlider.slider('getAttribute', 'lock_to_ticks');
expect(lockAttr).toBe(false);
});
it("Should set the slider value when `ticks[]` is not set", function() {
testSlider = $('#testSlider1').slider({
min: 0,
max: 10,
value: 1,
lock_to_ticks: true
});
testSlider.slider('setValue', 5);
var value = testSlider.slider('getValue');
expect(value).toBe(5);
});
it("Should return a value (after calling `setAttribute()`)", function() {
testSlider = $('#testSlider1').slider({
min: 0,
max: 10,
value: 1,
lock_to_ticks: true
});
// Try to lock to ticks when there are no ticks[]
testSlider.slider('setAttribute', 'lock_to_ticks', true);
testSlider.slider('setValue', 5);
// Without proper checking, getValue() is going to return NaN in this case
var value = testSlider.slider('getValue');
expect(isNaN(value)).toBe(false);
});
it("Should snap to closest tick value (single)", function() {
testSlider = $('#testSlider1').slider({
value: 1,
ticks: [1, 10, 50, 200, 500, 1000, 5000, 10000],
lock_to_ticks: true
});
// Set a value that is not a tick
testSlider.slider('setValue', 102);
var value = testSlider.slider('getValue');
expect(value).toBe(50);
});
it("Should snap to closest tick value (single, vertical)", function() {
testSlider = $('#testSlider1').slider({
value: 1,
ticks: [1, 10, 50, 200, 500, 1000, 5000, 10000],
lock_to_ticks: true,
orientation: 'vertical'
});
//selecting values that are not inside tickes
testSlider.slider('setValue', 102);
//getting the actual values. They should be the closest values from ticks (which are 1 and 50 on this case)
var value = testSlider.slider('getValue');
expect(value).toBe(50);
});
it("Should snap to closest tick value (range)", function() {
testSlider = $("#testSlider1").slider({
value: [1, 10000],
ticks: [1, 10, 50, 200, 500, 1000, 5000, 10000],
lock_to_ticks: true
});
//selecting values that are not inside tickes
testSlider.slider("setValue", [4, 102]);
//getting the actual values. They should be the closest values from ticks (which are 1 and 50 on this case)
var values = testSlider.slider("getValue");
expect(values[0]).toBe(1);
expect(values[1]).toBe(50);
});
it("Should snap to closest tick value (range, vertical)", function() {
testSlider = $("#testSlider1").slider({
value: [1, 10000],
ticks: [1, 10, 50, 200, 500, 1000, 5000, 10000],
lock_to_ticks: true,
orientation: 'vertical'
});
//selecting values that are not inside tickes
testSlider.slider("setValue", [4, 102]);
//getting the actual values. They should be the closest values from ticks (which are 1 and 50 on this case)
var values = testSlider.slider("getValue");
expect(values[0]).toBe(1);
expect(values[1]).toBe(50);
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});
/**
* The mouse navigation tests are based on the following slider properties:
*
* initial value: 3 or [3, 7]
* ticks: [0, 3, 5, 7, 10]
* step: 0.1
*
* When the values are in the range from 0 to 10 and the step is 0.1, every value
* can be represented as 1% of the range. For example, 5.5 is 55% and 5.6 is 56%.
* This makes it easier to test the behaviour of tick locking.
*
* The mouse clicks are based on a percentage that represents where the user clicked
* on the slider (60% = 6.0). The percentage is then used to calculate the coordinates
* for the mouse events (mousedown, mousemove, and mouseup).
*
* These tests are setup to test for all combinations of relevant slider configurations:
* single/range, horizontal/vertical orientation, LTR/RTL, and ordered/reversed.
* The tests also check that the handles have the correct positioning, which should
* match the ticks that the handles lock to.
*
* The test data was carefully chosen based on following the test logic below.
*
* The test logic for sliders:
* - Clicking to the left of the handle should not change its value
* - Clicking to the left of the handle should change its value and lock to another tick
* - Ditto for clicking to the right of the handle
*
* For range sliders, the same logic is applied except test both handle1 and handle2.
*/
describe("`lock_to_ticks: true` mouse navigation test cases", function() {
var initialValue = 3;
var initialRangeValues = [3, 7];
var tickValues = [0, 3, 5, 7, 10];
// Quick lookup from value to index
var tickIndexes = {0: 0, 3: 1, 5: 2, 7: 3, 10: 4};
var stepValue = 0.1;
var orientations = ['horizontal', 'vertical'];
var reversed = [false, true];
var sliderTypes = ['single', 'range'];
var rtl = [false, true];
var testCases = [];
var mouseEventArguments;
function calcMouseEventCoords(sliderElem, orientation, per) {
var sliderBB = sliderElem.getBoundingClientRect();
if (orientation === 'horizontal') {
return {
clientX: sliderBB.left + (sliderElem.offsetWidth * per / 100),
clientY: sliderBB.top
};
}
else if (orientation === 'vertical') {
return {
clientX: sliderBB.left,
clientY: sliderBB.top + (sliderElem.offsetHeight * per / 100)
};
}
}
beforeEach(function() {
// Set up default set of mouse event arguments
mouseEventArguments = [
'mousemove', // type
true, // canBubble
true, // cancelable
document, // view,
0, // detail
0, // screenX
0, // screenY
undefined, // clientX
undefined, // clientY,
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey,
0, // button
null // relatedTarget
];
});
function createMouseEvent(type, clientX, clientY) {
var mouseEvent = document.createEvent('MouseEvent');
mouseEventArguments[0] = type;
mouseEventArguments[7] = clientX;
mouseEventArguments[8] = clientY;
mouseEvent.initMouseEvent.apply(mouseEvent, mouseEventArguments);
return mouseEvent;
}
var mouseTestData = {
single: {
testData: [{
willChange: false,
expectedValue: initialValue,
percent: 20
}, {
willChange: true,
expectedValue: 0,
percent: 10
}, {
willChange: false,
expectedValue: initialValue,
percent: 40
}, {
willChange: true,
expectedValue: 5,
percent: 45
}],
// Modify test data for RTL and reversed situations.
altTestData: [{
willChange: false,
expectedValue: initialValue,
percent: 80
}, {
willChange: true,
expectedValue: 0,
percent: 90
}, {
willChange: false,
expectedValue: initialValue,
percent: 60
}, {
willChange: true,
expectedValue: 5,
percent: 55
}],
},
range: {
testData: [{
willChange: false,
expectedValue: initialRangeValues,
percent: 20
}, {
willChange: true,
expectedValue: [0, 7],
percent: 10
}, {
willChange: false,
expectedValue: initialRangeValues,
percent: 40
}, {
willChange: true,
expectedValue: [5, 7],
percent: 45
},
// More test data that will affect handle2
{
willChange: true,
expectedValue: [3, 5],
percent: 60
}, {
willChange: false,
expectedValue: initialRangeValues,
percent: 65
}, {
willChange: false,
expectedValue: initialRangeValues,
percent: 80
}, {
willChange: true,
expectedValue: [3, 10],
percent: 90
}],
// Modify test data for RTL and reversed situations.
// Here, the order of the ticks matter when locking a handle to a tick
// when there are two ticks that are equal in distance to lock to.
altTestData: [{
willChange: false,
expectedValue: initialRangeValues,
percent: 20
}, {
willChange: true,
expectedValue: [3, 10],
percent: 10
}, {
willChange: true,
expectedValue: [3, 5],
percent: 40
}, {
willChange: false,
expectedValue: initialRangeValues,
percent: 35
},
// More test data that will affect handle2
{
willChange: false,
expectedValue: initialRangeValues,
percent: 60
}, {
willChange: true,
expectedValue: [5, 7],
percent: 55
}, {
willChange: false,
expectedValue: initialRangeValues,
percent: 80
}, {
willChange: true,
expectedValue: [0, 7],
percent: 90
}],
}
};
sliderTypes.forEach(function(sliderType) {
orientations.forEach(function(orientation) {
rtl.forEach(function(isRTL) {
reversed.forEach(function(isReversed) {
var isHorizontal = orientation === 'horizontal';
var isVertical = orientation === 'vertical';
var isRange = sliderType === 'range';
var whichData;
var whichStyle;
whichData = mouseTestData[sliderType].testData;
if (isHorizontal) {
// XOR
// One or the other needs to be true
if ((isRTL && !isReversed) || (isReversed && !isRTL)) {
whichData = mouseTestData[sliderType].altTestData;
}
}
else if (isVertical) {
if (isReversed) {
whichData = mouseTestData[sliderType].altTestData;
}
}
if (isHorizontal) {
if (isRTL) {
whichStyle = 'right';
}
else {
whichStyle = 'left';
}
}
else if (isVertical) {
whichStyle = 'top';
}
testCases.push({
value: isRange ? initialRangeValues : initialValue,
step: stepValue,
range: isRange,
orientation: orientation,
reversed: isReversed,
rtl: 'auto',
isRTL: isRTL,
inputId: isRTL ? 'rtlSlider' : 'testSlider1',
testData: whichData,
stylePos: whichStyle
});
});
});
});
});
testCases.forEach(function(testCase) {
describe("range=" + testCase.range + ", orientation=" + testCase.orientation +
", rtl=" + testCase.isRTL + ", reversed=" + testCase.reversed, function() {
var $testSlider;
var $handle1;
var $handle2;
var sliderId;
var sliderOptions;
var $tick1;
var $tick2;
var $ticks;
beforeEach(function() {
sliderId = testCase.range ? 'myRangeSlider' : 'mySlider';
sliderOptions = {
id: sliderId,
step: testCase.step,
orientation: testCase.orientation,
value: testCase.value,
range: testCase.range,
lock_to_ticks: true,
reversed: testCase.reversed,
rtl: 'auto',
ticks: tickValues,
};
});
afterEach(function() {
if ($testSlider) {
$testSlider.slider('destroy');
$testSlider = null;
}
});
testCase.testData.forEach(function(testData) {
it("Should snap to closest tick (percent=" + testData.percent + ", changed=" + testData.willChange + ")", function(done) {
$testSlider = $('#'+testCase.inputId).slider(sliderOptions);
var sliderElem = $('#'+sliderId)[0];
$ticks = $('#'+sliderId).find('.slider-tick');
$handle1 = $('#'+sliderId).find('.slider-handle:first');
$handle2 = $('#'+sliderId).find('.slider-handle:last');
var coords = calcMouseEventCoords(sliderElem, testCase.orientation, testData.percent);
var checkMouseMove = function() {
var value = $testSlider.slider('getValue');
expect(value).toEqual(testData.expectedValue);
if (testCase.range) {
$tick1 = $ticks.eq(tickIndexes[testData.expectedValue[0]]);
$tick2 = $ticks.eq(tickIndexes[testData.expectedValue[1]]);
expect($handle1.css(testCase.stylePos)).toBe($tick1.css(testCase.stylePos));
expect($handle2.css(testCase.stylePos)).toBe($tick2.css(testCase.stylePos));
}
else {
$tick1 = $ticks.eq(tickIndexes[testData.expectedValue]);
expect($handle1.css(testCase.stylePos)).toBe($tick1.css(testCase.stylePos));
}
};
var checkMouseUp = function() {
var value = $testSlider.slider('getValue');
expect(value).toEqual(testData.expectedValue);
if (testCase.range) {
$tick1 = $ticks.eq(tickIndexes[testData.expectedValue[0]]);
$tick2 = $ticks.eq(tickIndexes[testData.expectedValue[1]]);
expect($handle1.css(testCase.stylePos)).toBe($tick1.css(testCase.stylePos));
expect($handle2.css(testCase.stylePos)).toBe($tick2.css(testCase.stylePos));
}
else {
$tick1 = $ticks.eq(tickIndexes[testData.expectedValue]);
expect($handle1.css(testCase.stylePos)).toBe($tick1.css(testCase.stylePos));
}
document.removeEventListener('mousemove', checkMouseMove, false);
document.removeEventListener('mouseup', checkMouseUp, false);
done();
};
sliderElem.addEventListener('mousedown', function() {
var value = $testSlider.slider('getValue');
expect(value).toEqual(testData.expectedValue);
// Check position of handles
if (testCase.range) {
$tick1 = $ticks.eq(tickIndexes[testData.expectedValue[0]]);
$tick2 = $ticks.eq(tickIndexes[testData.expectedValue[1]]);
expect($handle1.css(testCase.stylePos)).toBe($tick1.css(testCase.stylePos));
expect($handle2.css(testCase.stylePos)).toBe($tick2.css(testCase.stylePos));
}
else {
$tick1 = $ticks.eq(tickIndexes[testData.expectedValue]);
expect($handle1.css(testCase.stylePos)).toBe($tick1.css(testCase.stylePos));
}
document.addEventListener('mousemove', checkMouseMove, false);
document.addEventListener('mouseup', checkMouseUp, false);
});
sliderElem.dispatchEvent(createMouseEvent('mousedown', coords.clientX, coords.clientY));
document.dispatchEvent(createMouseEvent('mousemove', coords.clientX, coords.clientY));
document.dispatchEvent(createMouseEvent('mouseup', coords.clientX, coords.clientY));
});
});
});
});
});
/**
* The keyboard navigation tests are based on the following slider properties:
*
* initial value: 3 or [3, 7]
* ticks: [0, 3, 5, 7, 10]
* step: 0.1
*
* See description for mouse navigation tests for explanation for test setup values.
*
* These tests are setup to test for all combinations of relevant slider configurations:
* single/range, horizontal/vertical orientation, LTR/RTL, natural keys navigation,
* ordered/reversed, and all key presses (left, up, right, down).
*
* The test data is fairly straightforward and passes most configurations except for
* special cases when using natural key navigation. For these cases, the test data
* had to be 'inverted'. For example, the test data had to be inverted when the
* slider has a horizontal orientation with either RTL or reversed option set (but not both).
*
* The test logic for sliders:
* - Key to the left should change the value and lock to the tick to the left
* - Key to the right should change the value and lock to the tick to the right
*
* For range sliders, the same logic is applied except test both handle1 and handle2.
*/
describe("`lock_to_ticks: true` keyboard navigation test cases", function() {
var initialValue = 3;
var initialRangeValues = [3, 7];
var tickValues = [0, 3, 5, 7, 10];
var stepValue = 0.1;
var keyData = {
left: 37,
up: 38,
right: 39,
down: 40
};
var keys = ['left', 'up', 'right', 'down'];
var orientations = ['horizontal', 'vertical'];
var reversed = [false, true];
var naturalKeys = [false, true];
var ranged = [false, true];
var rtl = [false, true];
var rangeHandles = ['handle1', 'handle2'];
var testCases = [];
orientations.forEach(function(orientation) {
ranged.forEach(function(isRange) {
rtl.forEach(function(isRTL) {
naturalKeys.forEach(function(isNatural) {
reversed.forEach(function(isReversed) {
testCases.push({
value: isRange ? initialRangeValues : initialValue,
step: stepValue,
range: isRange,
orientation: orientation,
reversed: isReversed,
rtl: 'auto',
natural_arrow_keys: isNatural,
isRTL: isRTL,
inputId: isRTL ? 'rtlSlider' : 'testSlider1',
});
});
});
});
});
});
testCases.forEach(function(testCase) {
var handles = testCase.range ? rangeHandles : ['handle1'];
describe("orientation=" + testCase.orientation + ", range=" + testCase.range + ", rtl=" + testCase.isRTL +
", natural_arrow_keys=" + testCase.natural_arrow_keys +
", reversed=" + testCase.reversed, function() {
var $testSlider;
var $handle;
var keyboardEvent;
var sliderId;
var sliderOptions;
beforeEach(function() {
sliderId = testCase.range ? 'myRangeSlider' : 'mySlider';
sliderOptions = {
id: sliderId,
step: testCase.step,
orientation: testCase.orientation,
value: testCase.value,
range: testCase.range,
lock_to_ticks: true,
reversed: testCase.reversed,
rtl: 'auto',
natural_arrow_keys: testCase.natural_arrow_keys,
ticks: tickValues,
};
// Create keyboard event
keyboardEvent = document.createEvent('Event');
keyboardEvent.initEvent('keydown', true, true);
});
afterEach(function() {
keyboardEvent = null;
if ($testSlider) {
$testSlider.slider('destroy');
$testSlider = null;
}
});
handles.forEach(function(handleKey) {
keys.forEach(function(key) {
var isHorizontal = testCase.orientation === 'horizontal';
var isVertical = testCase.orientation === 'vertical';
var isRange = testCase.range;
var isRTL = testCase.isRTL;
var isReversed = testCase.reversed;
var isNatural = testCase.natural_arrow_keys;
var testData = {
keyCode: keyData[key],
handle1: {
expectedValue: null
},
handle2: {
expectedValue: null
}
};
if (isRange) {
// If initial value is [3, 7] Then
// These expected values will pass 96/128 tests (32 failures)
if (key === 'left' || key === 'down') {
testData.handle1.expectedValue = [0, 7];
testData.handle2.expectedValue = [3, 5];
}
else if (key === 'right' || key === 'up') {
testData.handle1.expectedValue = [5, 7];
testData.handle2.expectedValue = [3, 10];
}
// Special cases when using natural keys
if (isNatural) {
if ((isHorizontal && isReversed && !isRTL) ||
(isHorizontal && isRTL && !isReversed) ||
(isVertical && !isReversed))
{
if (key === 'left' || key === 'down') {
testData.handle1.expectedValue = [5, 7];
testData.handle2.expectedValue = [3, 10];
}
else if (key === 'right' || key === 'up') {
testData.handle1.expectedValue = [0, 7];
testData.handle2.expectedValue = [3, 5];
}
}
}
}
else {
// If initial value is 3 Then
// These expected values will pass 48/64 tests (16 failures)
if (key === 'left' || key === 'down') {
testData.handle1.expectedValue = 0;
}
else if (key === 'right' || key === 'up') {
testData.handle1.expectedValue = 5;
}
// Special cases when using natural keys
if (isNatural) {
// XOR
// One or the other needs to be true
if ((isHorizontal && isReversed && !isRTL) ||
(isHorizontal && isRTL && !isReversed) ||
(isVertical && !isReversed))
{
if (key === 'left' || key === 'down') {
testData.handle1.expectedValue = 5;
}
else if (key === 'right' || key === 'up') {
testData.handle1.expectedValue = 0;
}
}
}
}
it("Should lock to tick (" + handleKey + ", key=" + key + ")", function(done) {
$testSlider = $('#'+testCase.inputId).slider(sliderOptions);
$handle = $('#'+sliderId).find('.slider-handle:' + (handleKey === 'handle1' ? 'first' : 'last'));
$handle.on('keydown', function() {
var value = $testSlider.slider('getValue');
expect(value).toEqual(testData[handleKey].expectedValue);
done();
});
keyboardEvent.keyCode = keyboardEvent.which = testData.keyCode;
$handle[0].dispatchEvent(keyboardEvent);
});
});
});
});
});
});

View File

@@ -0,0 +1,92 @@
/*
*************************
Logarithmic Scale Tests
*************************
*/
describe("Slider with logarithmic scale tests", function() {
var testSlider;
describe("Should properly position the slider", function() {
function testSliderPosition(min, max, value){
testSlider = $("#testSlider1").slider({
min: min,
max: max,
scale: 'logarithmic',
value: value // This should be at 50%
});
var expectedPostition = 210 / 2 + 'px';
var handle = $("#testSlider1").prev('div.slider').find('.min-slider-handle');
expect(handle.css('left')).toBe(expectedPostition);
}
it("with positive values", function() {
testSliderPosition(1, 10000, 100);
});
it("with zero", function() {
testSliderPosition(0, 63, 7);
});
it("with a negative value", function() {
testSliderPosition(-7, 56, 0);
});
});
it("Should properly position the tick marks", function() {
testSlider = $("#testSlider1").slider({
min: 1,
max: 100,
scale: 'logarithmic',
ticks: [1,10,20,50,100]
});
// Position expected for the '10' tick
var expectedTickOnePosition = 210 / 2 + 'px'; //should be at 50%
var handle = $("#testSlider1").prev('div.slider').find(".slider-tick").eq(1);
expect(handle.css('left')).toBe(expectedTickOnePosition);
});
it("Should use step size when navigating the keyboard", function() {
testSlider = $("#testSlider1").slider({
min: 1,
max: 10000,
scale: 'logarithmic',
value: 100,
step: 5
});
// Focus on handle1
var handle1 = $("#testSlider1").prev('div.slider').find('.slider-handle');
handle1.focus();
// Create keyboard event
var keyboardEvent = document.createEvent("Events");
keyboardEvent.initEvent("keydown", true, true);
var keyPresses = 0;
handle1.on("keydown", function() {
keyPresses++;
var value = $("#testSlider1").slider('getValue');
expect(value).toBe(100 + keyPresses*5);
});
keyboardEvent.keyCode = keyboardEvent.which = 39; // RIGHT
for (var i = 0; i < 5; i++) {
handle1[0].dispatchEvent(keyboardEvent);
}
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});

View File

@@ -0,0 +1,224 @@
/*
**********************
Left/Right Track Tests
**********************
This spec has tests for checking that the widths of the left and right
segments are the correct widths and colors, based on their CSS.
*/
describe("Low/High Track Tests", function() {
var unstyledID = "low-high-slider";
var styledID = "low-high-slider-styled";
var testSlider;
describe("Single-value sliders, no styling", function() {
var id = unstyledID;
beforeEach(function() {
testSlider = $("#testSlider1").slider({
id: id,
min: 0,
max: 10,
value: 5
});
});
it("low track width is zero", function()
{
var leftTrack = $("#" + id + " .slider-track-low");
expect($(leftTrack).css("width")).toBe("0px");
});
it("high track width is 50%", function()
{
var rightTrack = $("#" + id + " .slider-track-high");
var trackWidth = rightTrack.parent().width();
expect($(rightTrack).css("width")).toBe((trackWidth / 2) + "px");
});
it("high track is transparent", function()
{
var rightTrack = $("#" + id + " .slider-track-high");
var rightColor = rightTrack.css("background-color");
var isTransparent = rightColor.match(/rgba\([0-9]{1,3}, [0-9]{1,3}, [0-9]{1,3}, 0\)/);
expect(isTransparent).toBeTruthy();
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});
describe("Single-value sliders, with styling", function() {
var id = styledID;
beforeEach(function() {
testSlider = $("#testSlider1").slider({
id: id,
min: 0,
max: 10,
value: 5
});
});
it("low track width is zero", function()
{
var leftTrack = $("#" + id + " .slider-track-low");
expect($(leftTrack).css("width")).toBe("0px");
});
it("high track width is 50%", function()
{
var rightTrack = $("#" + id + " .slider-track-high");
var trackWidth = rightTrack.parent().width();
expect($(rightTrack).css("width")).toBe((trackWidth / 2) + "px");
});
it("high track is red", function()
{
var rightTrack = $("#" + id + " .slider-track-high");
var rightColor = rightTrack.css("background-color");
expect(rightColor).toBe("rgb(255, 0, 0)");
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});
describe("Range sliders, no styling", function() {
var id = unstyledID;
var values = {
min: 0,
max: 10,
values: [ 4, 6 ]
};
beforeEach(function() {
testSlider = $("#testSlider1").slider({
id: id,
min: values.min,
max: values.max,
range: true,
value: values.values
});
});
it("low track width is correct", function()
{
var leftTrack = $("#" + id + " .slider-track-low");
var trackWidth = leftTrack.parent().width();
var expectedWidth = ((values.values[0] - values.min) / (values.max - values.min)) * trackWidth;
expect($(leftTrack).css("width")).toBe(expectedWidth + "px");
});
it("high track width is correct", function()
{
var rightTrack = $("#" + id + " .slider-track-high");
var trackWidth = rightTrack.parent().width();
var expectedWidth = ((values.max - values.values[1]) / (values.max - values.min)) * trackWidth;
expect($(rightTrack).css("width")).toBe(expectedWidth + "px");
});
it("low track is transparent", function()
{
var leftTrack = $("#" + id + " .slider-track-low");
var leftColor = leftTrack.css("background-color");
var isTransparent = leftColor.match(/rgba\([0-9]{1,3}, [0-9]{1,3}, [0-9]{1,3}, 0\)/);
expect(isTransparent).toBeTruthy();
});
it("high track is transparent", function()
{
var rightTrack = $("#" + id + " .slider-track-high");
var rightColor = rightTrack.css("background-color");
var isTransparent = rightColor.match(/rgba\([0-9]{1,3}, [0-9]{1,3}, [0-9]{1,3}, 0\)/);
expect(isTransparent).toBeTruthy();
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});
describe("Range sliders, with styling", function() {
var id = styledID;
var values = {
min: 0,
max: 10,
values: [ 4, 6 ]
};
beforeEach(function() {
testSlider = $("#testSlider1").slider({
id: id,
min: values.min,
max: values.max,
range: true,
value: values.values
});
});
it("low track width is correct", function()
{
var leftTrack = $("#" + id + " .slider-track-low");
var trackWidth = leftTrack.parent().width();
var expectedWidth = ((values.values[0] - values.min) / (values.max - values.min)) * trackWidth;
expect($(leftTrack).css("width")).toBe(expectedWidth + "px");
});
it("high track width is correct", function()
{
var rightTrack = $("#" + id + " .slider-track-high");
var trackWidth = rightTrack.parent().width();
var expectedWidth = ((values.max - values.values[1]) / (values.max - values.min)) * trackWidth;
expect($(rightTrack).css("width")).toBe(expectedWidth + "px");
});
it("low track is green", function()
{
var leftTrack = $("#" + id + " .slider-track-low");
var leftColor = leftTrack.css("background-color");
expect(leftColor).toBe("rgb(0, 255, 0)");
});
it("high track is red", function()
{
var rightTrack = $("#" + id + " .slider-track-high");
var rightColor = rightTrack.css("background-color");
expect(rightColor).toBe("rgb(255, 0, 0)");
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});
});

View File

@@ -0,0 +1,74 @@
describe("Namespace Tests", function() {
var sourceJS = "temp/bootstrap-slider.js";
var defaultNamespace = 'slider';
var alternateNamespace = 'bootstrapSlider';
it("should always set the plugin namespace to 'bootstrapSlider'", function(done) {
$.getScript(sourceJS, function() {
expect($.fn.bootstrapSlider).toBeDefined();
done();
});
});
it("should set the plugin namespace to 'slider' if the namespace is available", function(done) {
$.getScript(sourceJS, function() {
expect($.fn.slider).toBeDefined();
done();
});
});
it("should print a console warning if the 'slider' namespace is already bound", function(done) {
$.fn.slider = function() {};
spyOn(window.console, "warn");
$.getScript(sourceJS, function() {
var expectedWarningMessage = "bootstrap-slider.js - WARNING: $.fn.slider namespace is already bound. Use the $.fn.bootstrapSlider namespace instead.";
expect(window.console.warn).toHaveBeenCalledWith(expectedWarningMessage);
done();
});
});
it("Should not create instance when 'slider' namespace is in use", function(done) {
$.fn.slider = function() {}; // Overwrite temporarily
$.getScript(sourceJS, function() {
var $testSlider = $('#testSlider1').bootstrapSlider();
var sliderInst = $testSlider.data(defaultNamespace);
expect(sliderInst).toBeUndefined();
$testSlider.bootstrapSlider('destroy');
done();
});
});
it("Should create instance associated with the alternate 'bootstrapSlider' namespace", function(done) {
$.fn.slider = function() {};
$.getScript(sourceJS, function() {
var $testSlider = $('#testSlider1').bootstrapSlider();
var sliderInst = $testSlider.data(alternateNamespace);
expect(sliderInst).toBeTruthy();
$testSlider.bootstrapSlider('destroy');
done();
});
});
afterEach(function(done) {
/*
Set the namespaces back to undefined and reload slider
So that namespace is returned to $.fn.slider
*/
$.fn.bootstrapSlider = undefined;
$.fn.slider = undefined;
$.getScript(sourceJS, function() {
done();
});
});
});

View File

@@ -0,0 +1,75 @@
describe("Orientation Tests", function() {
var testSlider;
var sliderHandleTopPos;
var sliderHandleLeftPos;
describe("Vertical", function() {
beforeEach(function() {
testSlider = new Slider("#orientationSlider", {
id: "orientationSliderId",
orientation: "vertical",
min: 0,
max: 10,
value: 5
});
var sliderHandleEl = document.querySelector("#orientationSliderId .slider-handle");
var sliderHandleBoundingBoxInfo = sliderHandleEl.getBoundingClientRect();
sliderHandleTopPos = sliderHandleBoundingBoxInfo.top;
sliderHandleLeftPos = sliderHandleBoundingBoxInfo.left;
});
afterEach(function() {
if(testSlider) {
testSlider.destroy();
}
});
it("slides up when handle moves upwards", function() {
var mousemove = document.createEvent('MouseEvents');
var mousemoveX = sliderHandleLeftPos;
var mousemoveY = sliderHandleTopPos - 100;
var newSliderValue;
mousemove.initMouseEvent(
"mousedown",
true /* bubble */,
true /* cancelable */,
window,
null,
0, 0, mousemoveX, mousemoveY, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/,
null
);
testSlider.sliderElem.dispatchEvent(mousemove);
newSliderValue = testSlider.getValue();
expect(newSliderValue).toBeLessThan(5);
});
it("slides down when handle moves downwards", function() {
var mousemove = document.createEvent('MouseEvents');
var mousemoveX = sliderHandleLeftPos;
var mousemoveY = sliderHandleTopPos + 100;
var newSliderValue;
mousemove.initMouseEvent(
"mousedown",
true /* bubble */,
true /* cancelable */,
window,
null,
0, 0, mousemoveX, mousemoveY, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/,
null
);
testSlider.sliderElem.dispatchEvent(mousemove);
newSliderValue = testSlider.getValue();
expect(newSliderValue).toBeGreaterThan(5);
});
});
}); // End of spec

View File

@@ -0,0 +1,660 @@
describe("Public Method Tests", function() {
var testSlider;
describe("slider constructor", function() {
describe("returns a jQuery object if it is called on a jQuery object with zero or more matching elements", function() {
it("returns a jQuery object if it is called on with no matching elements", function() {
testSlider = $();
expect(testSlider.slider() instanceof jQuery).toBe(true);
});
it("returns a jQuery object if it is called on with one matching element", function() {
testSlider = $('#testSlider1');
expect(testSlider.slider() instanceof jQuery).toBe(true);
});
it("returns a jQuery object if it is called on with multiple matching elements", function() {
testSlider = $('#testSlider1, #testSlider2');
expect(testSlider.slider() instanceof jQuery).toBe(true);
});
});
it("reads and sets the 'id' attribute of the slider instance that is created", function() {
var sliderId = "mySlider";
testSlider = $("#testSlider1").slider({
id : sliderId
});
var sliderInstanceHasExpectedId = $("#testSlider1").siblings("div.slider").is("#" + sliderId);
expect(sliderInstanceHasExpectedId).toBeTruthy();
});
it("generates multiple slider instances from selector", function() {
$(".makeSlider").slider();
var sliderInstancesExists = $(".makeSlider").siblings().is(".slider");
expect(sliderInstancesExists).toBeTruthy();
var sliderInstancesCount = $(".makeSlider").siblings(".slider").length;
expect(sliderInstancesCount).toEqual(2);
$('.makeSlider').slider('destroy');
});
it("reads and sets the 'min' option properly", function() {
var minVal = -5;
testSlider = $("#testSlider1").slider({
min : minVal
});
testSlider.slider('setValue', minVal);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(minVal);
});
it("reads and sets the 'max' option properly", function() {
var maxVal = 15;
testSlider = $("#testSlider1").slider({
max : maxVal
});
testSlider.slider('setValue', maxVal);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(maxVal);
});
it("reads and sets the 'precision' option properly", function() {
testSlider = $("#testSlider1").slider({
precision: 2
});
testSlider.slider('setValue', 8.115);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(8.12);
});
it("reads and sets the 'orientation' option properly", function() {
var orientationVal = "vertical";
testSlider = $("#testSlider1").slider({
orientation : orientationVal
});
var orientationClassApplied = $("#testSlider1").siblings("div.slider").hasClass("slider-vertical");
expect(orientationClassApplied).toBeTruthy();
});
it("reads and sets the 'value' option properly", function() {
var val = 8;
testSlider = $("#testSlider1").slider({
value : val
});
testSlider.slider('setValue', val);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(val);
});
it("reads and sets the 'selection' option properly", function() {
var selectionVal = "after",
maxSliderVal = 10;
testSlider = $("#testSlider1").slider({
selection : selectionVal
});
testSlider.slider('setValue', maxSliderVal);
var sliderSelectionWidthAtMaxValue = $("#testSlider1").siblings(".slider").children("div.slider-track").children("div.slider-selection").width();
expect(sliderSelectionWidthAtMaxValue).toBe(0);
});
it("updates the 'selection' option properly", function() {
var selectionVal = "none",
maxSliderVal = 10;
testSlider = $("#testSlider1").slider({
selection : selectionVal
});
testSlider.slider('setValue', maxSliderVal);
testSlider.slider('refresh');
var sliderSelectionHasHideClass_A = $("#testSlider1").siblings(".slider").children("div.slider-track").children("div.slider-track-low").hasClass('hide');
expect(sliderSelectionHasHideClass_A).toBe(true);
var sliderSelectionHasHideClass_B = $("#testSlider1").siblings(".slider").children("div.slider-track").children("div.slider-selection").hasClass('hide');
expect(sliderSelectionHasHideClass_B).toBe(true);
var sliderSelectionHasHideClass_C = $("#testSlider1").siblings(".slider").children("div.slider-track").children("div.slider-track-high").hasClass('hide');
expect(sliderSelectionHasHideClass_C).toBe(true);
var newSelectionVal = 'after';
testSlider.slider('setAttribute', 'selection', newSelectionVal);
testSlider.slider('refresh');
var sliderSelectionHasHideClass_D = $("#testSlider1").siblings(".slider").children("div.slider-track").children("div.slider-track-low").hasClass('hide');
expect(sliderSelectionHasHideClass_D).toBe(false);
var sliderSelectionHasHideClass_E = $("#testSlider1").siblings(".slider").children("div.slider-track").children("div.slider-selection").hasClass('hide');
expect(sliderSelectionHasHideClass_E).toBe(false);
var sliderSelectionHasHideClass_F = $("#testSlider1").siblings(".slider").children("div.slider-track").children("div.slider-track-high").hasClass('hide');
expect(sliderSelectionHasHideClass_F).toBe(false);
});
it("reads and sets the 'handle' option properly", function() {
var handleVal = "triangle";
testSlider = $("#testSlider1").slider({
handle : handleVal
});
var handleIsSetToTriangle = $("#testSlider1").siblings(".slider").children("div.slider-handle").hasClass("triangle");
expect(handleIsSetToTriangle).toBeTruthy();
});
it("reads and sets the 'reversed' option properly", function() {
var reversedVal = true,
maxSliderVal = 10;
testSlider = $("#testSlider1").slider({
reversed : reversedVal
});
testSlider.slider('setValue', maxSliderVal);
var sliderSelectionHeightAtMaxValue = $("#testSlider1").siblings(".slider").children("div.slider-track").children("div.slider-selection").width();
expect(sliderSelectionHeightAtMaxValue).toBe(0);
});
it("reads and sets the 'formatter' option properly", function() {
var tooltipFormatter = function(value) {
return 'Current value: ' + value;
};
testSlider = $("#testSlider1").slider({
formatter : tooltipFormatter
});
testSlider.slider('setValue', 9);
var tooltipMessage = $("#testSlider1").siblings(".slider").find("div.tooltip").children("div.tooltip-inner").text();
var expectedMessage = tooltipFormatter(9);
expect(tooltipMessage).toBe(expectedMessage);
});
it("reads and sets the 'enabled' option properly", function() {
testSlider = $("#testSlider1").slider({
enabled: false
});
var isEnabled = testSlider.slider('isEnabled');
expect(isEnabled).not.toBeTruthy();
});
describe("reads and sets the 'tooltip' option properly", function() {
it("tooltip is not shown if set to 'hide'", function() {
testSlider = $("#testSlider1").slider({
tooltip : "hide"
});
var tooltipIsHidden = testSlider.siblings(".slider").children("div.tooltip").hasClass("hide");
expect(tooltipIsHidden).toBeTruthy();
});
it("tooltip is shown during sliding if set to 'show'", function() {
testSlider = $("#testSlider1").slider({
tooltip : "show"
});
var tooltipIsHidden = !($("#testSlider1").siblings(".slider").children("div.tooltip").hasClass("in"));
expect(tooltipIsHidden).toBeTruthy();
// Trigger hover
var mouseenterEvent = document.createEvent("Events");
mouseenterEvent.initEvent("mouseenter", true, true);
testSlider.data('slider').sliderElem.dispatchEvent(mouseenterEvent);
var tooltipIsShownAfterSlide = $("#testSlider1").siblings(".slider").children("div.tooltip").hasClass("in");
expect(tooltipIsShownAfterSlide).toBeTruthy();
});
it("tooltip is shown on mouse over and hides correctly after mouse leave", function() {
testSlider = $("#testSlider1").slider({
tooltip : "show"
});
var tooltipIsHidden = !($("#testSlider1").siblings(".slider").children("div.tooltip").hasClass("in"));
expect(tooltipIsHidden).toBeTruthy();
// Trigger hover
var mouseenterEvent = document.createEvent("Events");
mouseenterEvent.initEvent("mouseenter", true, true);
testSlider.data('slider').sliderElem.dispatchEvent(mouseenterEvent);
var tooltipIsShownAfterSlide = $("#testSlider1").siblings(".slider").children("div.tooltip").hasClass("in");
expect(tooltipIsShownAfterSlide).toBeTruthy();
// Trigger leave
var mouseleaveEvent = document.createEvent("Events");
mouseleaveEvent.initEvent("mouseleave", true, true);
testSlider.data('slider').sliderElem.dispatchEvent(mouseleaveEvent);
var tooltipIsAgainHidden = !($("#testSlider1").siblings(".slider").children("div.tooltip").hasClass("in"));
expect(tooltipIsAgainHidden).toBeTruthy();
});
it("tooltip is always shown if set to 'always'", function() {
testSlider = $("#testSlider1").slider({
tooltip : "always"
});
var tooltipIsShown = $("#testSlider1").siblings(".slider").children("div.tooltip").hasClass("in");
expect(tooltipIsShown).toBeTruthy();
});
it("defaults to 'show' option if invalid value is passed", function() {
testSlider = $("#testSlider1").slider({
tooltip : "invalid option value"
});
var tooltipIsHidden = !($("#testSlider1").siblings(".slider").children("div.tooltip").hasClass("in"));
expect(tooltipIsHidden).toBeTruthy();
// Trigger hover
var mouseenterEvent = document.createEvent("Events");
mouseenterEvent.initEvent("mouseenter", true, true);
testSlider.data('slider').sliderElem.dispatchEvent(mouseenterEvent);
var tooltipIsShownOnHover = $("#testSlider1").siblings(".slider").children("div.tooltip").hasClass("in");
expect(tooltipIsShownOnHover).toBeTruthy();
});
});
});
describe("'setValue()' tests", function() {
var formatInvalidInputMsg = function(invalidValue) { return "Invalid input value '" + invalidValue + "' passed in"; };
describe("if slider is a single value slider", function() {
beforeEach(function() {
testSlider = $("#testSlider1").slider();
});
it("properly sets the value of the slider when given a numeric value", function() {
var valueToSet = 5;
testSlider.slider('setValue', valueToSet);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(valueToSet);
});
it("properly sets the value of the slider when given a string value", function(){
var valueToSet = "5";
testSlider.slider('setValue', valueToSet);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(5);
});
it("if a value passed in is greater than the max (10), the slider only goes to the max", function() {
var maxValue = 10,
higherThanSliderMaxVal = maxValue + 5;
testSlider.slider('setValue', higherThanSliderMaxVal);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(maxValue);
});
it("if a value passed in is less than the min (0), the slider only goes to the min", function() {
var minValue = 0,
lowerThanSliderMaxVal = minValue - 5;
testSlider.slider('setValue', lowerThanSliderMaxVal);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(minValue);
});
it("sets the 'value' property of the slider <input> element", function() {
var value = 9;
testSlider.slider('setValue', value);
var currentValue = document.querySelector("#testSlider1").value;
currentValue = parseFloat(currentValue);
expect(currentValue).toBe(value);
});
it("sets the 'value' attribute of the slider <input> element", function() {
var value = 9;
testSlider.slider('setValue', value);
var currentValue = document.querySelector("#testSlider1").getAttribute("value");
currentValue = parseFloat(currentValue);
expect(currentValue).toBe(value);
});
describe("when an invalid value type is passed in", function() {
var invalidValue;
beforeEach(function() {
invalidValue = "a";
});
it("throws an error and does not alter the slider value", function() {
var originalSliderValue = testSlider.slider('getValue');
var settingValue = function() {
testSlider.slider('setValue', invalidValue);
};
expect(settingValue).toThrow(new Error( formatInvalidInputMsg(invalidValue) ));
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(originalSliderValue);
});
});
});
describe("if slider is a range slider", function() {
beforeEach(function() {
testSlider = $("#testSlider1").slider({
value : [3, 8]
});
});
it("properly sets the values if both within the max and min", function() {
var valuesToSet = [5, 7];
testSlider.slider('setValue', valuesToSet);
var sliderValues = testSlider.slider('getValue');
expect(sliderValues[0]).toBe(valuesToSet[0]);
expect(sliderValues[1]).toBe(valuesToSet[1]);
});
describe("caps values to the min if they are set to be less than the min", function() {
var minValue = -5,
otherValue = 7;
it("first value is capped to min", function() {
testSlider.slider('setValue', [minValue, otherValue]);
var sliderValues = testSlider.slider('getValue');
expect(sliderValues[0]).toBe(0);
});
it("second value is capped to min", function() {
testSlider.slider('setValue', [otherValue, minValue]);
var sliderValues = testSlider.slider('getValue');
expect(sliderValues[1]).toBe(0);
});
});
describe("caps values to the max if they are set to be higher than the max", function() {
var maxValue = 15,
otherValue = 7;
it("first value is capped to max", function() {
testSlider.slider('setValue', [maxValue, otherValue]);
var sliderValues = testSlider.slider('getValue');
expect(sliderValues[0]).toBe(10);
});
it("second value is capped to max", function() {
testSlider.slider('setValue', [otherValue, maxValue]);
var sliderValues = testSlider.slider('getValue');
expect(sliderValues[1]).toBe(10);
});
});
describe("if either value is of invalid type", function() {
var invalidValue = "a",
otherValue = 7;
it("first value is of invalid type", function() {
var setSliderValueFn = function() {
testSlider.slider('setValue', [invalidValue, otherValue]);
};
expect(setSliderValueFn).toThrow(new Error( formatInvalidInputMsg(invalidValue) ));
});
it("second value is of invalid type", function() {
var setSliderValueFn = function() {
testSlider.slider('setValue', [otherValue, invalidValue]);
};
expect(setSliderValueFn).toThrow(new Error( formatInvalidInputMsg(invalidValue) ));
});
});
});
describe("triggerSlideEvent argument", function() {
it("if triggerSlideEvent argument is true, the 'slide' event is triggered", function() {
var testSlider = $("#testSlider1").slider({
value : 3
});
var newSliderVal = 5;
testSlider.on('slide', function(evt) {
expect(newSliderVal).toEqual(evt.value);
});
testSlider.slider('setValue', newSliderVal, true);
});
it("if triggerSlideEvent argument is false, the 'slide' event is not triggered", function() {
var newSliderVal = 5;
var slideEventTriggered = false;
var testSlider = $("#testSlider1").slider({
value : 3
});
testSlider.on('slide', function() {
slideEventTriggered = true;
});
testSlider.slider('setValue', newSliderVal, false);
expect(slideEventTriggered).toEqual(false);
});
});
describe("triggerChangeEvent argument", function() {
it("if triggerChangeEvent argument is true, the 'change' event is triggered", function() {
var testSlider = $("#testSlider1").slider({
value : 3
});
var newSliderVal = 5;
testSlider.on('change', function(evt) {
expect(newSliderVal).toEqual(evt.value.newValue);
});
testSlider.slider('setValue', newSliderVal, true);
});
it("if triggerChangeEvent argument is false, the 'change' event is not triggered", function() {
var changeEventTriggered = false;
var testSlider = $("#testSlider1").slider({
value : 3
});
testSlider.on('change', function() {
changeEventTriggered = true;
});
testSlider.slider('setValue', 5, false);
expect(changeEventTriggered).toEqual(false);
});
});
});
describe("'getValue()' tests", function() {
it("returns the current value of the slider", function() {
testSlider = $("#testSlider1").slider();
var valueToSet = 5;
testSlider.slider('setValue', valueToSet);
var sliderValue = testSlider.slider('getValue');
expect(sliderValue).toBe(valueToSet);
});
});
describe("'enable()' tests", function() {
it("correctly enables a slider", function() {
testSlider = $("#testSlider1").slider({
enabled: false
});
testSlider.slider("enable");
var isEnabled = testSlider.slider("isEnabled");
expect(isEnabled).toBeTruthy();
});
});
describe("'disable()' tests", function() {
it("correctly disable a slider", function() {
testSlider = $("#testSlider1").slider();
testSlider.slider("disable");
var isEnabled = testSlider.slider("isEnabled");
expect(isEnabled).not.toBeTruthy();
});
});
describe("'toggle()' tests", function() {
it("correctly enables a disabled slider", function() {
testSlider = $("#testSlider1").slider({
enabled: false
});
testSlider.slider("toggle");
var isEnabled = testSlider.slider("isEnabled");
expect(isEnabled).toBeTruthy();
});
it("correctly disables an enabled slider", function() {
testSlider = $("#testSlider1").slider();
testSlider.slider("toggle");
var isEnabled = testSlider.slider("isEnabled");
expect(isEnabled).not.toBeTruthy();
});
});
describe("'isEnabled()' tests", function() {
it("returns true for an enabled slider", function() {
testSlider = $("#testSlider1").slider({
id: "enabled",
enabled: true
});
var isEnabled = testSlider.slider("isEnabled");
var $slider = testSlider.siblings("#enabled");
var hasDisabledClass = $slider.hasClass("slider") && $slider.hasClass("#enabled");
expect(isEnabled).toBeTruthy();
expect(hasDisabledClass).not.toBeTruthy();
});
it("returns false for a disabled slider", function() {
testSlider = $("#testSlider1").slider({
id: "disabled",
enabled: false
});
var isEnabled = testSlider.slider("isEnabled");
var $slider = testSlider.siblings("#disabled");
var hasDisabledClass = $slider.hasClass("slider") && $slider.hasClass("slider-disabled");
expect(isEnabled).not.toBeTruthy();
expect(hasDisabledClass).toBeTruthy();
});
});
it("get attribute", function() {
testSlider = $("#testSlider1").slider();
var sliderMaxValue = testSlider.slider('getAttribute', 'max');
expect(sliderMaxValue).toBe(10);
});
it("changes slider from basic to range", function() {
testSlider = $("#makeRangeSlider").slider();
testSlider.slider('setAttribute', 'range', true).slider('refresh');
var isRangeSlider = $("#changeOrientationSlider").parent("div.slider").find('.slider-handle').last().hasClass('hide');
expect(isRangeSlider).toBeFalsy();
});
it("setAttribute: changes the 'data-slider-orientation' property from horizontal to vertical", function() {
testSlider = $("#changeOrientationSlider").slider({
id: "changeOrientationSliderElem"
});
testSlider.slider('setAttribute', 'orientation', 'vertical').slider('refresh');
var $slider = $("#changeOrientationSliderElem");
var orientationClassApplied = $slider.hasClass("slider-vertical");
expect(orientationClassApplied).toBeTruthy();
});
it("relayout: if slider is not displayed on initialization and then displayed later on, relayout() will not adjust the margin-left of the tooltip", function() {
// Setup
testSlider = new Slider("#relayoutSliderInput", {
id: "relayoutSlider",
min: 0,
max: 10,
value: 5
});
var mainTooltipDOMRef = document.querySelector("#relayoutSlider .tooltip-main");
var relayoutSliderContainerDOMRef = document.querySelector("#relayoutSliderContainer");
var tooltipMarginLeft;
// Main tooltip margin-left offset should not be set on slider intialization
tooltipMarginLeft = parseFloat(mainTooltipDOMRef.style.marginLeft);
expect(tooltipMarginLeft).toBeNaN();
// Show slider and call relayout()
relayoutSliderContainerDOMRef.style.display = "block";
testSlider.relayout();
// Main tooltip margin-left offset should not be set after relayout() is called.
tooltipMarginLeft = Math.abs( parseFloat(mainTooltipDOMRef.style.marginLeft) );
expect(tooltipMarginLeft).toBeNaN();
});
it("relayout: if slider is not displayed on initialization and then displayed later on, relayout() will re-adjust the tick label width", function() {
// Setup
testSlider = new Slider("#relayoutSliderInputTickLabels", {
id: "relayoutSliderTickLabels",
min: 0,
max: 10,
ticks: [0, 5, 10],
ticks_labels: ['low', 'mid', 'high'],
value: 5
});
var $ticks = $('#relayoutSliderTickLabels').find('.slider-tick-label');
// Tick-Width should be 0 on slider intialization
var i, $tick;
for (i = 0; i < $ticks.length; i++) {
$tick = $($ticks[i]);
expect( parseInt($tick.css('width')) ).toBe(0);
}
// Show slider and call relayout()
$('#relayoutSliderContainerTickLabels').css('display', 'block');
testSlider.relayout();
$('#relayoutSliderContainerTickLabels').css('display', 'none');
// Tick-Width should re-adjust to be > 0
for (i = 0; i < $ticks.length; i++) {
$tick = $($ticks[i]);
expect( parseInt($tick.css('width')) ).toBeGreaterThan(0);
}
});
afterEach(function() {
if(testSlider) {
if(testSlider instanceof jQuery) { testSlider.slider('destroy'); }
if(testSlider instanceof Slider) { testSlider.destroy(); }
testSlider = null;
}
});
});

View File

@@ -0,0 +1,224 @@
/*
RangeHighlights Render Tests
*/
describe("RangeHighlights Render Tests", function() {
var testSlider1;
var testSlider2;
var testSlider3;
var testSlider4;
//setup
beforeEach(function() {
var rangeHighlightsOpts1 = [
{ "start": 2, "end": 5, "class": "category1" }, // left: 10%; width: 15%
{ "start": 7, "end": 8, "class": "category2" }, // left: 35%; width: 5%
{ "start": 17, "end": 19 }, // left: 85%; width: 10%
{ "start": 17, "end": 24 }, //out of range - not visible
{ "start": -3, "end": 19 } //out of range - not visible
];
var rangeHighlightsOpts2 = [
{ "start": 2, "end": 5, "class": "category1" }, // top: 10%; height: 15%
{ "start": 7, "end": 8, "class": "category2" }, // top: 35%; height: 5%
{ "start": 17, "end": 19 }, // top: 85%; height: 10%
{ "start": 7, "end": -4 }, //out of range - not visible
{ "start": 23, "end": 15 } //out of range - not visible
];
testSlider1 = $('#testSlider1').slider({
id: 'slider1',
min: 0,
max: 20,
step: 1,
value: 14,
rangeHighlights: rangeHighlightsOpts1
});
testSlider2 = $('#testSlider2').slider({
id: 'slider2',
min: 0,
max: 20,
step: 1,
value: 14,
orientation: 'vertical',
rangeHighlights: rangeHighlightsOpts2
});
testSlider3 = $('#testSlider3').slider({
id: 'slider3',
min: 0,
max: 20,
step: 1,
value: 14,
reversed: true,
rangeHighlights: rangeHighlightsOpts1
});
testSlider4 = $('#testSlider4').slider({
id: 'slider4',
min: 0,
max: 20,
step: 1,
value: 14,
reversed: true,
orientation: 'vertical',
rangeHighlights: rangeHighlightsOpts2
});
});
//cleanup
afterEach(function() {
testSlider1.slider('destroy');
testSlider1 = null;
testSlider2.slider('destroy');
testSlider2 = null;
testSlider3.slider('destroy');
testSlider3 = null;
testSlider4.slider('destroy');
testSlider4 = null;
});
//test the visibility of ranges e.g. : { "start": 23, "end": 15 } - out of range - not visible
function testHighlightedElements(sliderId, isHorizontal, expections) {
//check elements exist
it("Highlighted ranges are rendered - " + sliderId, function() {
expect($(sliderId).length).toBe(1);
expect($(sliderId + ' .slider-rangeHighlight').length).toBe(5);
expect($(sliderId + ' .slider-rangeHighlight.category1').length).toBe(1);
expect($(sliderId + ' .slider-rangeHighlight.category2').length).toBe(1);
});
//check elements exist within proper display value
it("Highlighted ranges render inside the slider's bounds " + sliderId, function() {
expect($(sliderId).length).toBe(1);
var ranges = $(sliderId + ' .slider-rangeHighlight');
expect(ranges.length).toBe(5);
for (var i = 0; i < ranges.length; i++) {
expect($(ranges[i]).is(":visible")).toBe(expections[i].isVisible);
if (expections[i].isVisible) {
if(isHorizontal) {
expect(_getLeftPercent($(ranges[i]))).toBe(expections[i].start);
expect(_getWidthPercent($(ranges[i]))).toBe(expections[i].size);
} else {
expect(_getTopPercent($(ranges[i]))).toBe(expections[i].start);
expect(_getHeightPercent($(ranges[i]))).toBe(expections[i].size);
}
}
}
});
}
function _getLeftPercent(element) {
return Math.round(100 * element.position().left / element.parent().width()) + '%';
}
function _getWidthPercent(element) {
var width = element.width();
var parentWidth = element.offsetParent().width();
return Math.round(100 * width / parentWidth) + '%';
}
function _getTopPercent(element) {
return Math.round(100 * element.position().top / element.parent().height()) + '%';
}
function _getHeightPercent(element) {
var height = element.height();
var parentHeight = element.offsetParent().height();
return Math.round(100 * height / parentHeight) + '%';
}
//test both testSlider
testHighlightedElements('#slider1', true, [{
isVisible: true,
start: '10%',
size: '15%'
}, {
isVisible: true,
start: '35%',
size: '5%'
}, {
isVisible: true,
start: '85%',
size: '10%'
}, {
isVisible: false,
start: '85%',
size: '10%'
}, {
isVisible: false,
start: '85%',
size: '10%'
}]);
testHighlightedElements('#slider2', false, [{
isVisible: true,
start: '10%',
size: '15%'
}, {
isVisible: true,
start: '35%',
size: '5%'
}, {
isVisible: true,
start: '85%',
size: '10%'
}, {
isVisible: false,
start: '85%',
size: '10%'
}, {
isVisible: false,
start: '85%',
size: '10%'
}]);
testHighlightedElements('#slider3', true, [{
isVisible: true,
start: '75%',
size: '15%'
}, {
isVisible: true,
start: '60%',
size: '5%'
}, {
isVisible: true,
start: '5%',
size: '10%'
}, {
isVisible: false,
start: '5%',
size: '10%'
}, {
isVisible: false,
start: '5%',
size: '10%'
}]);
testHighlightedElements('#slider4', false, [{
isVisible: true,
start: '75%',
size: '15%'
}, {
isVisible: true,
start: '60%',
size: '5%'
}, {
isVisible: true,
start: '5%',
size: '10%'
}, {
isVisible: false,
start: '5%',
size: '10%'
}, {
isVisible: false,
start: '5%',
size: '10%'
}]);
});

View File

@@ -0,0 +1,122 @@
describe("refresh() Method Tests", function() {
var testSlider;
var $testSlider;
var options;
var initialValue, initialRangeValue;
var newValue, newRangeValue;
beforeEach(function() {
initialValue = 5;
initialRangeValue = [4, 5];
newValue = 7;
newRangeValue = [7, 10];
options = {
id: 'mySlider',
min: 0,
max: 10,
step: 1,
value: initialValue
};
});
afterEach(function() {
if(testSlider) {
testSlider.destroy();
testSlider = null;
}
if ($testSlider) {
$testSlider.slider('destroy');
$testSlider = null;
}
});
it("does not convert a non-range slider into a range slider when invoked", function() {
// Initialize non-range slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5
});
// Assert that slider is non-range slider
var initialValue = testSlider.getValue();
var sliderIsRangeValue = initialValue instanceof Array;
expect(sliderIsRangeValue).toBeFalsy();
// Invoke refresh() method
testSlider.refresh();
// Assert that slider remains a non-range slider
var afterRefreshValue = testSlider.getValue();
sliderIsRangeValue = afterRefreshValue instanceof Array;
expect(sliderIsRangeValue).toBeFalsy();
});
it("should reset slider to its default value on refresh", function() {
// Initialize non-range slider
testSlider = new Slider('#testSlider1', options);
testSlider.setValue(newValue, true, true);
testSlider.refresh();
expect(testSlider.getValue()).toBe(initialValue);
});
it("should maintain its current value on refresh", function() {
// Initialize non-range slider
testSlider = new Slider('#testSlider1', options);
testSlider.setValue(newValue, true, true);
testSlider.refresh({ useCurrentValue: true });
expect(testSlider.getValue()).toBe(newValue);
});
it("should reset slider to its default value on refresh (jQuery)", function() {
// Initialize non-range slider
$testSlider = $('#testSlider1').slider(options);
$testSlider.slider('setValue', newValue, true, true);
$testSlider.slider('refresh');
expect($testSlider.slider('getValue')).toBe(initialValue);
});
it("should maintain its current value on refresh (jQuery)", function() {
// Initialize non-range slider
$testSlider = $('#testSlider1').slider(options);
$testSlider.slider('setValue', newValue, true, true);
$testSlider.slider('refresh', { useCurrentValue: true });
expect($testSlider.slider('getValue')).toBe(newValue);
});
it("should reset slider to its default value on refresh (range)", function() {
// Initialize range slider
options.value = initialRangeValue;
options.range = true;
testSlider = new Slider('#testSlider1', options);
testSlider.setValue(newRangeValue, true, true);
testSlider.refresh();
expect(testSlider.getValue()).toBe(initialRangeValue);
});
it("should maintain its current value on refresh (range)", function() {
// Initialize range slider
options.value = initialRangeValue;
options.range = true;
testSlider = new Slider('#testSlider1', options);
testSlider.setValue(newRangeValue, true, true);
testSlider.refresh({ useCurrentValue: true });
expect(testSlider.getValue()).toBe(newRangeValue);
});
}); // End of spec

View File

@@ -0,0 +1,70 @@
describe("Resize Tests", function() {
var testSlider, dataSlider;
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
dataSlider = null;
}
});
describe("Tick Labels", function() {
var $el, options;
beforeEach(function() {
var tick = [0, 100, 200, 300, 400];
options = {
ticks: tick,
ticks_labels: ['$0', '$100', '$200', '$300', '$400']
};
});
it("should resize the tick labels when horizontal", function() {
$el = $("#resizeSlider");
testSlider = $el.slider(options);
dataSlider = testSlider.data('slider');
$('.slider').width(210);
dataSlider._resize();
expect($el.siblings('div.slider').find('.slider-tick-label:eq(0)').width()).toBe(53);
$('.slider').width(120);
dataSlider._resize();
expect($el.siblings('div.slider').find('.slider-tick-label:eq(0)').width()).toBe(30);
$('.slider').width(900);
dataSlider._resize();
expect($el.siblings('div.slider').find('.slider-tick-label:eq(1)').width()).toBe(225);
$('.slider').width(210);
dataSlider._resize();
expect($el.siblings('div.slider').find('.slider-tick-label:eq(0)').width()).toBe(53);
});
it('should resize the tick labels when vertical', function() {
var $el = $("#resizeSliderVertical");
testSlider = $el.slider(options);
dataSlider = testSlider.data('slider');
$('.slider').height(210);
dataSlider._resize();
expect($el.siblings('div.slider').find('.slider-tick-label:eq(0)').height()).toBe(53);
$('.slider').height(120);
dataSlider._resize();
expect($el.siblings('div.slider').find('.slider-tick-label:eq(0)').height()).toBe(30);
$('.slider').height(900);
dataSlider._resize();
expect($el.siblings('div.slider').find('.slider-tick-label:eq(1)').height()).toBe(225);
$('.slider').height(210);
dataSlider._resize();
expect($el.siblings('div.slider').find('.slider-tick-label:eq(0)').height()).toBe(53);
});
});
}); // End of spec

View File

@@ -0,0 +1,81 @@
describe("RTL Tests", function() {
var testSlider;
afterEach(function() {
if(testSlider) {
testSlider.destroy();
testSlider = null;
}
});
describe("rtl slider tests", function() {
it("should be rtl by default inside an rtl wrapper", function() {
testSlider = new Slider("#rtlSlider");
var dirIsRtl = $("#rtlSlider").siblings().is(".slider-rtl");
expect(dirIsRtl).toBeTruthy();
});
it("rtl to false inside an rtl wrapper", function() {
testSlider = new Slider("#rtlSlider", {
rtl: false
});
var dirIsRtl = $("#rtlSlider").siblings().is(".slider-rtl");
expect(dirIsRtl).not.toBeTruthy();
});
it("rtl to true inside an ltr wrapper", function() {
testSlider = new Slider("#testSlider1", {
rtl: true
});
var dirIsRtl = $("#testSlider1").siblings().is(".slider-rtl");
expect(dirIsRtl).toBeTruthy();
});
it("slider use inversed left and right inline style", function() {
testSlider = new Slider("#rtlSlider", {
min: 0,
max: 10,
value: 5
});
var sliderTrackLowRight=$("#rtlSlider").siblings(".slider-rtl").children("div.slider-track").children("div.slider-track-low").css("right");
var sliderSelectionRight=$("#rtlSlider").siblings(".slider-rtl").children("div.slider-track").children("div.slider-selection").css("right");
var sliderTrackHighLeft=$("#rtlSlider").siblings(".slider-rtl").children("div.slider-track").children("div.slider-track-high").css("left");
expect(sliderTrackLowRight).toBe("0px");
expect(sliderSelectionRight).toBe("0%");
expect(sliderTrackHighLeft).toBe("0px");
});
it("tooltip position must be inversed in vertical", function() {
testSlider = new Slider("#rtlSlider", {
orientation: "vertical",
});
var mainTooltipHasClassLeft = testSlider.tooltip.classList.contains("left");
expect(mainTooltipHasClassLeft).toBeTruthy();
expect(testSlider.tooltip.style.right).toBe("100%");
});
it("tooltip position can be forced in vertical", function() {
testSlider = new Slider("#rtlSlider", {
orientation: "vertical",
tooltip_position: "right",
});
var mainTooltipHasClassRight = testSlider.tooltip.classList.contains("right");
expect(mainTooltipHasClassRight).toBeTruthy();
expect(testSlider.tooltip.style.left).toBe("100%");
});
});
}); // End of spec

View File

@@ -0,0 +1,150 @@
describe("Scrollable body test", function() {
var testSlider;
var sliderHandleTopPos;
var sliderHandleLeftPos;
describe("Vertical scrolled body", function() {
beforeEach(function() {
testSlider = new Slider("#veryLowPositionedSlider", {
id: "scrollTestSliderId",
orientation: "vertical",
min: 0,
max: 20,
value: 10,
step: 1
});
document.body.scrollTop = 2000;
var sliderHandleEl = document.querySelector("#scrollTestSliderId .slider-handle");
var sliderHandleBoundingBoxInfo = sliderHandleEl.getBoundingClientRect();
sliderHandleTopPos = sliderHandleBoundingBoxInfo.top;
sliderHandleLeftPos = sliderHandleBoundingBoxInfo.left;
});
afterEach(function() {
if(testSlider) {
testSlider.destroy();
}
document.body.scrollTop = 0;
});
// The difference between sliderHandleTopPos and mousemoveY is equal to 50 in both cases,
// but difference between initial and final slider value is not equal (6 and 4).
// It happens because we don't 'hit' the center of handle but the top left corner.
it("slides up when handle moves upwards after scroll page down", function() {
var mousemove = document.createEvent('MouseEvents');
var mousemoveX = sliderHandleLeftPos;
var mousemoveY = sliderHandleTopPos - 50;
var newSliderValue;
mousemove.initMouseEvent(
"mousedown",
true /* bubble */,
true /* cancelable */,
window,
null,
0, 0, mousemoveX, mousemoveY, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/,
null
);
testSlider.sliderElem.dispatchEvent(mousemove);
newSliderValue = testSlider.getValue();
expect(newSliderValue).toEqual(4);
});
it("slides down when handle moves downwards after scroll page down", function() {
var mousemove = document.createEvent('MouseEvents');
var mousemoveX = sliderHandleLeftPos;
var mousemoveY = sliderHandleTopPos + 50;
var newSliderValue;
mousemove.initMouseEvent(
"mousedown",
true /* bubble */,
true /* cancelable */,
window,
null,
0, 0, mousemoveX, mousemoveY, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/,
null
);
testSlider.sliderElem.dispatchEvent(mousemove);
newSliderValue = testSlider.getValue();
expect(newSliderValue).toEqual(14);
});
});
describe('Horizontal scrolled body', function() {
beforeEach(function() {
testSlider = new Slider('#offRightEdgeSliderInput', {
id: 'offRightEdgeSlider',
orientation: 'horizontal',
min: 0,
max: 20,
value: 10,
step: 1,
});
testSlider.sliderElem.scrollIntoView();
var handle = document.querySelector('#offRightEdgeSlider .slider-handle');
var handleRect = handle.getBoundingClientRect();
sliderHandleTopPos = handleRect.top;
sliderHandleLeftPos = handleRect.left;
});
afterEach(function() {
if (testSlider) {
testSlider.destroy();
}
window.scrollTo(0, 0);
});
it('slides left when clicked on the left of the handle', function() {
var x = sliderHandleLeftPos - 50;
var y = sliderHandleTopPos;
var mousedown, newSliderValue;
mousedown = createMouseDownEvent(x, y);
testSlider.sliderElem.dispatchEvent(mousedown);
newSliderValue = testSlider.getValue();
expect(newSliderValue).toEqual(4);
});
it('slides right when clicked on the left of the handle', function() {
var x = sliderHandleLeftPos + 50;
var y = sliderHandleTopPos;
var mousedown, newSliderValue;
mousedown = createMouseDownEvent(x, y);
testSlider.sliderElem.dispatchEvent(mousedown);
newSliderValue = testSlider.getValue();
expect(newSliderValue).toEqual(14);
});
function createMouseDownEvent(x, y) {
var mousedown = document.createEvent('MouseEvents');
mousedown.initMouseEvent(
'mousedown',
false /* bubble */,
true /* cancelable */,
window, /* view */
null, /* detail */
0, 0, x, y, /* coordinates */
false, false, false, false, /* modifier keys */
0, /* button: left */
null /* relatedTarget */
);
return mousedown;
}
});
});

View File

@@ -0,0 +1,85 @@
describe("Scrollable test", function() {
var testSlider;
var sliderHandleTopPos;
var sliderHandleLeftPos;
var scrollableContainer;
describe("Vertical inside scrollable container", function() {
beforeEach(function() {
testSlider = new Slider("#ex1", {
id: "ex1Slider",
orientation: "vertical",
min: 0,
max: 20,
value: 10,
step: 1
});
scrollableContainer = document.querySelector('#scrollable-div');
scrollableContainer.scrollTop = 145;
var sliderHandleEl = document.querySelector("#ex1Slider .slider-handle");
var sliderHandleBoundingBoxInfo = sliderHandleEl.getBoundingClientRect();
sliderHandleTopPos = sliderHandleBoundingBoxInfo.top;
sliderHandleLeftPos = sliderHandleBoundingBoxInfo.left;
});
afterEach(function() {
if(testSlider) {
testSlider.destroy();
}
});
// The difference between sliderHandleTopPos and mousemoveY is equal to 50 in both cases,
// but difference between initial and final slider value is not equal (6 and 4).
// It happens because we don't 'hit' the center of handle but the top left corner.
it("slides up when handle moves upwards inside scrollable element after scrolling", function() {
var mousemove = document.createEvent('MouseEvents');
var mousemoveX = sliderHandleLeftPos;
var mousemoveY = sliderHandleTopPos - 50;
var newSliderValue;
mousemove.initMouseEvent(
"mousedown",
true /* bubble */,
true /* cancelable */,
window,
null,
0, 0, mousemoveX, mousemoveY, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/,
null
);
testSlider.sliderElem.dispatchEvent(mousemove);
newSliderValue = testSlider.getValue();
expect(newSliderValue).toEqual(4);
});
it("slides down when handle moves downwards inside scrollable element after scrolling", function() {
var mousemove = document.createEvent('MouseEvents');
var mousemoveX = sliderHandleLeftPos;
var mousemoveY = sliderHandleTopPos + 50;
var newSliderValue;
mousemove.initMouseEvent(
"mousedown",
true /* bubble */,
true /* cancelable */,
window,
null,
0, 0, mousemoveX, mousemoveY, /* coordinates */
false, false, false, false, /* modifier keys */
0 /*left*/,
null
);
testSlider.sliderElem.dispatchEvent(mousemove);
newSliderValue = testSlider.getValue();
expect(newSliderValue).toEqual(14);
});
});
}); // End of spec

View File

@@ -0,0 +1,61 @@
describe("TickMaxValueNotATickBehavior", function() {
var SLIDER_ID = "testSlider1";
var slider;
var options;
describe('max value should be reached', function() {
beforeEach(function() {
options = {
min: 40,
max: 1310,
step: 5,
scale: "logarithmic",
value: 44
};
slider = new Slider(document.getElementById(SLIDER_ID), options);
});
it("Value should contain max value when slider is moved to outer right position", function() {
var sliderLeft = slider.sliderElem.offsetLeft;
var offsetY = slider.sliderElem.offsetTop;
// I think the + 10 work because it is half of the handle size;
var offsetX = sliderLeft + slider.sliderElem.clientWidth + 10;
var expectedValue = slider.options.max;
var mouseEvent = getMouseDownEvent(offsetX, offsetY);
slider.mousedown(mouseEvent);
// FIXME: Use 'mouseup' event type
slider.mouseup(mouseEvent);
expect(slider.getValue()).toBe(expectedValue);
});
});
afterEach(function() {
slider.destroy();
});
// helper functions
function getMouseDownEvent(offsetXToClick, offsetYToClick) {
var args = [
'mousedown', // type
true, // canBubble
true, // cancelable
document, // view,
0, // detail
0, // screenX
0, // screenY
offsetXToClick, // clientX
offsetYToClick, // clientY,
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey,
0, // button
null // relatedTarget
];
var event = document.createEvent('MouseEvents');
event.initMouseEvent.apply(event, args);
return event;
}
});

View File

@@ -0,0 +1,108 @@
describe("TickClickingBehavior", function() {
var SLIDER_ID = "testSlider1";
var slider;
var options;
describe('ticks start with 0', function() {
beforeEach(function() {
options = {
ticks: [0, 1, 2, 3, 4],
ticks_positions: [0, 25, 50, 75, 100],
step: 1,
value: 4
};
slider = new Slider(document.getElementById(SLIDER_ID), options);
});
it("Should set slider to corresponding value when ticks are clicked", function() {
for (var i = 0; i < options.ticks.length; i++) {
clickTickAtIndexAndVerify(slider, i);
}
});
});
describe('ticks start with positive value', function() {
beforeEach(function() {
options = {
ticks: [1, 2, 3, 4, 5],
ticks_positions: [0, 25, 50, 75, 100],
step: 1,
value: 5
};
slider = new Slider(document.getElementById(SLIDER_ID), options);
});
it("Should set slider to corresponding value when ticks are clicked", function() {
for (var i = 0; i < options.ticks.length; i++) {
clickTickAtIndexAndVerify(slider, i);
}
});
});
describe('ticks start with negative value', function() {
beforeEach(function() {
options = {
ticks: [-5, -4, -3, -2, -1],
ticks_positions: [0, 25, 50, 75, 100],
step: 1,
value: -1
};
slider = new Slider(document.getElementById(SLIDER_ID), options);
});
it("Should set slider to corresponding value when ticks are clicked", function() {
for (var i = 0; i < options.ticks.length; i++) {
clickTickAtIndexAndVerify(slider, i);
}
});
});
afterEach(function() { slider.destroy(); });
// helper functions
function clickTickAtIndexAndVerify(slider, tickIndex) {
var sliderLeft = slider.sliderElem.offsetLeft;
var tickLeft = slider.ticks[tickIndex].offsetLeft;
var handleHalfWidth = $('.slider-handle.round').width() / 2;
var offsetX = sliderLeft + tickLeft + handleHalfWidth;
var offsetY = slider.sliderElem.offsetTop;
var mouseEvent = getMouseDownEvent(offsetX, offsetY);
slider.mousedown(mouseEvent);
// FIXME: Use 'mouseup' event type
slider.mouseup(mouseEvent);
var expectedValue = slider.options.ticks[tickIndex];
expect(slider.getValue()).toBe(expectedValue);
}
function getMouseDownEvent(offsetXToClick, offsetYToClick) {
var args = [
'mousedown', // type
true, // canBubble
true, // cancelable
document, // view,
0, // detail
0, // screenX
0, // screenY
offsetXToClick, // clientX
offsetYToClick, // clientY,
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey,
0, // button
null // relatedTarget
];
var event = document.createEvent('MouseEvents');
event.initMouseEvent.apply(event, args);
return event;
}
});

View File

@@ -0,0 +1,253 @@
/*
Tick label Render Tests - Tests that labels render in correct positions in both horizontal and vertical orientation
*/
describe("Tick Label Render Tests", function() {
var testSliderH;
var testSliderV;
//setup
beforeEach(function() {
testSliderH = $('#testSlider1').slider({
id: 'slider1',
ticks: [0, 1, 2],
ticks_labels:['x', 'y', 'z'],
orientation:'horizontal'
});
testSliderV = $('#testSlider2').slider({
id: 'slider2',
ticks: [0, 1, 2],
ticks_labels:['x', 'y', 'z'],
orientation:'vertical'
});
});
//cleanup
afterEach(function() {
testSliderH.slider('destroy');
testSliderH = null;
testSliderV.slider('destroy');
testSliderV = null;
});
//e.g. testOrientation('horizontal', 2) will test the horizontal
//code path using control with the id testSlider2
function testOrientation(orientation) {
var sliderIndex = orientation.toLowerCase() === 'horizontal' ? 1 : 2;
var isVertical = orientation.toLowerCase() === 'horizontal' ? false : true;
var sliderId = '#slider' + sliderIndex;
//check elements exist
it("Tick labels are rendered - " + orientation, function() {
expect($(sliderId).length).toBe(1);
var length = $(sliderId + ' .slider-tick-label').length;
expect(length).toBe(3);
});
//check elements exist within the bounds of the slider
it("Tick labels render inside the slider's bounds" + orientation, function() {
expect($(sliderId).length).toBe(1);
var sliderRect = $(sliderId)[0].getBoundingClientRect();
var tickLabels = $(sliderId + ' .slider-tick-label');
for (var i = 0; i < tickLabels.length; i++) {
var labelRect = tickLabels[i].getBoundingClientRect();
if (isVertical) {
expect(labelRect.left).toBeGreaterThan(sliderRect.left);
expect(labelRect.top + 10 >= sliderRect.top).toBeTruthy();
} else {
expect(labelRect.top + 10 >= sliderRect.top).toBeTruthy();
expect(labelRect.width / 2 + labelRect.left >= sliderRect.left).toBeTruthy();
}
}
});
}
//test both horizontal and vertical orientations
testOrientation('horizontal');
testOrientation('vertical');
});
describe("Tick Labels 'is-selection' and 'in-selection' Tests", function() {
var $inputSlider;
var options;
var keyboardEvent;
var $slider;
var $handle1;
var $handle2;
var $tickLabels;
var tickLabelCount;
// Setup
beforeEach(function() {
options = {
id: 'slider1',
ticks: [0, 1, 2, 3, 4],
value: 2,
ticks_labels:['$0', '$1', '$2', '$3', '$4'],
};
tickLabelCount = options.ticks_labels.length;
// Create keyboard event
keyboardEvent = document.createEvent('Event');
keyboardEvent.initEvent('keydown', true, true);
});
// Cleanup
afterEach(function() {
$inputSlider.slider('destroy');
$inputSlider = null;
});
describe("Tick Labels 'is-selection' Tests", function() {
describe("'options.selection = 'before'", function() {
beforeEach(function() {
options.selection = 'before';
$inputSlider = $('#testSlider1').slider(options);
$slider = $('#slider1');
$tickLabels = $slider.find('.slider-tick-label-container div.slider-tick-label');
});
it("Should show the correct tick labels as 'is-selection'", function() {
// There should only be one tick label with the 'label-is-selection' class
expect($slider.find('.label-is-selection').length).toBe(1);
// Only the third tick label should have the 'label-is-selection' class
expect($tickLabels.eq(2).hasClass('label-is-selection')).toBe(true);
});
it("Should show the correct tick labels as 'is-selection' when keying to the left", function(done) {
$handle1 = $('#slider1').find('.slider-handle:first');
expect($slider.find('.label-is-selection').length).toBe(1);
expect($tickLabels.eq(2).hasClass('label-is-selection')).toBe(true);
$handle1.on('keydown', function() {
expect($slider.find('.label-is-selection').length).toBe(1);
expect($tickLabels.eq(1).hasClass('label-is-selection')).toBe(true);
done();
});
// Move handle1 to the left with keyboard
$handle1.focus();
keyboardEvent.keyCode = keyboardEvent.which = 37;
$handle1[0].dispatchEvent(keyboardEvent);
});
});
describe("'options.selection = 'after'", function() {
beforeEach(function() {
options.selection = 'after';
$inputSlider = $('#testSlider1').slider(options);
$slider = $('#slider1');
$tickLabels = $slider.find('.slider-tick-label-container div.slider-tick-label');
});
it("Should show the correct tick labels as 'is-selection'" , function() {
expect($slider.find('.label-is-selection').length).toBe(1);
expect($tickLabels.eq(2).hasClass('label-is-selection')).toBe(true);
});
it("Should show the correct tick labels as 'is-selection' when keying to the right" , function(done) {
$handle1 = $('#slider1').find('.slider-handle:first');
expect($slider.find('.label-is-selection').length).toBe(1);
expect($tickLabels.eq(2).hasClass('label-is-selection')).toBe(true);
$handle1.on('keydown', function() {
expect($slider.find('.label-is-selection').length).toBe(1);
expect($tickLabels.eq(3).hasClass('label-is-selection')).toBe(true);
done();
});
// Move handle1 to the right with keyboard
$handle1.focus();
keyboardEvent.keyCode = keyboardEvent.which = 39;
$handle1[0].dispatchEvent(keyboardEvent);
});
});
});
describe("Tick Labels 'in-selection' Tests", function() {
function checkTickLabels($labels, expectedLabels) {
var next = 0;
// There are only 5 tick labels.
expect($labels.length).toBe(tickLabelCount);
for (var i = 0; i < tickLabelCount; i++) {
if (i === expectedLabels[next]) {
expect($labels.eq(i).hasClass('label-in-selection')).toBe(true);
next++;
}
else {
expect($labels.eq(i).hasClass('label-in-selection')).toBe(false);
}
}
}
// Setup
beforeEach(function() {
options.value = [1, 3];
$inputSlider = $('#testSlider1').slider(options);
$slider = $('#slider1');
$tickLabels = $slider.find('.slider-tick-label-container div.slider-tick-label');
});
it("Should show the correct tick labels as 'in-selection'", function() {
expect($slider.find('.label-is-selection').length).toBe(3);
checkTickLabels($tickLabels, [1, 2, 3]);
});
it("Should show the correct tick labels as 'in-selection' when keying to the left", function(done) {
$handle1 = $('#slider1').find('.slider-handle:first');
// There should be 3 tick labels with the 'label-in-selection' class
expect($slider.find('.label-in-selection').length).toBe(3);
// Check that the correct tick labels have the 'label-in-selection' class
checkTickLabels($tickLabels, [1, 2, 3]);
$handle1.on('keydown', function() {
expect($slider.find('.label-in-selection').length).toBe(4);
// Check the labels again
checkTickLabels($tickLabels, [0, 1, 2, 3]);
done();
});
// Move handle1 to the left with keyboard
$handle1.focus();
keyboardEvent.keyCode = keyboardEvent.which = 37;
$handle1[0].dispatchEvent(keyboardEvent);
});
it("Should show the correct tick labels as 'in-selection' when keying to the right" , function(done) {
$handle2 = $('#slider1').find('.slider-handle:last');
expect($slider.find('.label-in-selection').length).toBe(3);
checkTickLabels($tickLabels, [1, 2, 3]);
$handle2.on('keydown', function() {
expect($slider.find('.label-in-selection').length).toBe(4);
checkTickLabels($tickLabels, [1, 2, 3, 4]);
done();
});
// Move handle2 to the right with keyboard
$handle2.focus();
keyboardEvent.keyCode = keyboardEvent.which = 39;
$handle2[0].dispatchEvent(keyboardEvent);
});
});
});

View File

@@ -0,0 +1,247 @@
/*
*************************
Tick Marks Tests
*************************
Verify that the number of tick marks matches what you set
Verify the tick marks are at the correct intervals
*/
describe("Slider with ticks tests", function() {
var testSlider;
it("Should have the number of tick marks you specify", function() {
testSlider = $("#testSlider1").slider({
ticks: [100, 200, 300, 400, 500]
});
var numTicks = $("#testSlider1").siblings('div.slider').find('.slider-tick').length;
expect(numTicks).toBe(5);
});
it("Should be at the default positions", function() {
testSlider = $("#testSlider1").slider({
ticks: [100, 200, 300, 400, 500]
});
$("#testSlider1").siblings('div.slider').find('.slider-tick').each(function(i) {
expect(this.style.left).toBe(100 * i / 4.0 + '%');
});
});
it("Should be at the positions you specify", function() {
var tickPositions = [0, 10, 20, 30, 100];
testSlider = $("#testSlider1").slider({
ticks: [100, 200, 300, 400, 500],
ticks_positions: tickPositions
});
$("#testSlider1").siblings('div.slider').find('.slider-tick').each(function(i) {
expect(this.style.left).toBe(tickPositions[i] + '%');
});
});
it("Should have the tick labels you specify", function() {
var tickLabels = ['$0', '$100', '$200', '$300', '$400'];
testSlider = $("#testSlider1").slider({
ticks: [100, 200, 300, 400, 500],
ticks_labels: tickLabels
});
var tickLabelElements = $("#testSlider1").siblings('div.slider').find('.slider-tick-label');
expect(tickLabelElements.length).toBe(tickLabels.length);
tickLabelElements.each(function(i) {
expect(this.innerHTML).toBe(tickLabels[i]);
});
});
it("Should not snap to a tick within tick bounds when using the keyboard navigation", function() {
testSlider = $("#testSlider1").slider({
ticks: [100, 200, 300, 400, 500],
ticks_snap_bounds: 30
});
// Focus on handle1
var handle1 = $("#testSlider1").prev('div.slider').find('.slider-handle');
handle1.focus();
// Create keyboard event
var keyboardEvent = document.createEvent("Events");
keyboardEvent.initEvent("keydown", true, true);
var keyPresses = 0;
handle1.on("keydown", function() {
keyPresses++;
var value = $("#testSlider1").slider('getValue');
expect(value).toBe(100 + keyPresses);
});
keyboardEvent.keyCode = keyboardEvent.which = 39; // RIGHT
for (var i = 0; i < 5; i++) {
handle1[0].dispatchEvent(keyboardEvent);
}
});
it("Should show the correct tick marks as 'in-selection', according to the `selection` property", function() {
var options = {
ticks: [100, 200, 300, 400, 500],
value: 250,
selection: 'after'
},
$el = $("#testSlider1");
testSlider = $el.slider(options);
expect($el.siblings('div.slider').find('.in-selection').length).toBe(3);
testSlider.slider('destroy');
options.selection = 'before';
testSlider = $el.slider(options);
expect($el.siblings('div.slider').find('.in-selection').length).toBe(2);
});
it("Should reverse the tick labels if `reversed` option is set to true", function() {
var ticks = [100, 200, 300, 400, 500];
var ticksLabels = ["$100", "$200", "$300", "$400", "$500"];
// Create reversed slider
testSlider = $("#testSlider1").slider({
id: "testSlider1Ref",
ticks: ticks,
ticks_labels: ticksLabels,
ticks_snap_bounds: 30,
reversed: true
});
// Assert that tick marks are reversed
var tickLabelsFromDOM = $("#testSlider1Ref .slider-tick-label-container")
.children(".slider-tick-label")
.map(function() { return $(this).text(); })
.toArray();
var reversedTickLabels = ticksLabels.reverse();
expect(tickLabelsFromDOM).toEqual(reversedTickLabels);
});
it("Should reverse the tick labels if `reversed` option is set to true and `ticks_positions` is specified", function() {
var ticks = [0, 100, 200, 300, 400];
var ticksLabels = ["$0", "$100", "$200", "$300", "$400"];
// Create reversed slider
testSlider = $("#testSlider1").slider({
id: "testSlider1Ref",
ticks: ticks,
ticks_labels: ticksLabels,
ticks_positions: [0, 30, 70, 90, 100],
ticks_snap_bounds: 20,
value: 200,
reversed: true
});
// Assert that tick marks are reversed
var tickLabelsFromDOM = $("#testSlider1Ref .slider-tick-label-container .slider-tick-label")
.sort(function(tickLabelElemA, tickLabelElemB) {
var leftOffsetA = $(tickLabelElemA).position().left;
var leftOffsetB = $(tickLabelElemB).position().left;
return leftOffsetA - leftOffsetB;
})
.map(function() { return $(this).text(); })
.toArray();
var reversedTickLabels = ticksLabels.reverse();
expect(tickLabelsFromDOM).toEqual(reversedTickLabels);
});
it("should wrap all of the ticks within a div with classname '.slider-tick-container'", function() {
// Create the slider with ticks
var ticks = [0, 100, 200, 300, 400, 600];
var $sliderDOMRef = $("#testSlider1");
// Create reversed slider
testSlider = $sliderDOMRef.slider({
id: "testSlider1Ref",
ticks: ticks,
ticks_positions: [0, 30, 70, 90, 100, 130]
});
// Assert that the ticks are children of the container element
var numTicks = $sliderDOMRef.siblings('div.slider').find('.slider-tick-container > .slider-tick').length;
expect(numTicks).toBe(ticks.length);
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});
describe("Slider min/max settings", function() {
var $inputSlider;
afterEach(function() {
if ($inputSlider) {
if ($inputSlider instanceof jQuery) {
$inputSlider.slider('destroy');
}
$inputSlider = null;
}
});
it("Should use min/max tick values for min/max settings", function() {
$inputSlider = $('#testSlider1').slider({
ticks: [1, 2, 3]
});
expect($inputSlider.slider('getAttribute', 'min')).toBe(1);
expect($inputSlider.slider('getAttribute', 'max')).toBe(3);
});
it("Should not overwrite 'min' setting", function() {
$inputSlider = $('#testSlider1').slider({
min: 0,
ticks: [1, 2, 3]
});
expect($inputSlider.slider('getAttribute', 'min')).toBe(0);
expect($inputSlider.slider('getAttribute', 'max')).toBe(3);
});
it("Should not overwrite 'max' setting", function() {
$inputSlider = $('#testSlider1').slider({
max: 5,
ticks: [1, 2, 3]
});
expect($inputSlider.slider('getAttribute', 'min')).toBe(1);
expect($inputSlider.slider('getAttribute', 'max')).toBe(5);
});
it("Should not overwrite 'min' or max' settings", function() {
$inputSlider = $('#testSlider1').slider({
min: 0,
max: 5,
ticks: [1, 2, 3]
});
expect($inputSlider.slider('getAttribute', 'min')).toBe(0);
expect($inputSlider.slider('getAttribute', 'max')).toBe(5);
});
it("Should ignore the ticks when outside of min/max range", function() {
$inputSlider = $("#testSlider1").slider({
ticks: [100, 200, 300, 400, 500],
min: 15000,
max: 25000
});
expect($inputSlider.slider('getAttribute', 'min')).toBe(15000);
expect($inputSlider.slider('getAttribute', 'max')).toBe(25000);
});
});

View File

@@ -0,0 +1,445 @@
describe("'ticks_tooltip' Option tests", function() {
var testSlider;
var mouseEventArguments;
beforeEach(function() {
// Set up default set of mouse event arguments
mouseEventArguments = [
'mousemove', // type
true, // canBubble
true, // cancelable
document, // view,
0, // detail
0, // screenX
0, // screenY
undefined, // clientX
undefined, // clientY,
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey,
0, // button
null // relatedTarget
];
});
describe("ticks_tooltip states", function() {
it("should have the tooltip above the last hovered over element", function() {
testSlider = new Slider(document.getElementById("testSlider1"), {
ticks: [0, 1, 2, 3, 4, 5, 6],
ticks_positions: [0, 19, 29, 39, 49, 95, 100],
step: 1,
value: 4,
ticks_tooltip: true,
orientation: 'horizontal'
});
mouseEventArguments[8] = testSlider.sliderElem.offsetTop; // clientY
var mouse49 = document.createEvent('MouseEvents');
mouseEventArguments[7] = testSlider.ticks[4].offsetLeft + testSlider.sliderElem.offsetLeft; // clientX
mouse49.initMouseEvent.apply(mouse49, mouseEventArguments);
var mouse95 = document.createEvent('MouseEvents');
mouseEventArguments[7] = testSlider.ticks[5].offsetLeft + testSlider.sliderElem.offsetLeft; // clientX
mouse95.initMouseEvent.apply(mouse95, mouseEventArguments);
var mouse100 = document.createEvent('MouseEvents');
mouseEventArguments[7] = testSlider.ticks[6].offsetLeft + testSlider.sliderElem.offsetLeft; // clientX
mouse100.initMouseEvent.apply(mouse100, mouseEventArguments);
var mouseStart = document.createEvent('MouseEvents');
mouseEventArguments[7] = testSlider.ticks[0].offsetLeft + testSlider.sliderElem.offsetLeft; // clientX
mouseStart.initMouseEvent.apply(mouseStart, mouseEventArguments);
//Simulate random movements
testSlider.mousedown(mouse49);
testSlider.mousemove(mouse95);
// FIXME: Use 'mouseup' event type
testSlider.mouseup(mouse95);
testSlider.mousedown(mouse49);
testSlider.mousemove(mouse100);
testSlider.mousemove(mouse95);
testSlider.mousemove(mouse95);
testSlider.mousemove(mouseStart);
expect(testSlider.tooltip.style.left).toBe("0%");
});
});
describe("Always show the tooltip", function() {
it("Should always display the tooltip after hovering over a tick", function(done) {
testSlider = new Slider(document.getElementById("testSlider1"), {
id: 'mySlider',
min: 0,
max: 10,
step: 1,
value: 1,
ticks: [0, 5, 10],
tooltip: 'always',
ticks_tooltip: true,
orientation: 'horizontal'
});
var bigOffset = 100000;
var isTooltipVisible = $('#mySlider').find('.tooltip.tooltip-main').hasClass('in');
expect(isTooltipVisible).toBe(true);
var mouseenter = document.createEvent('MouseEvent');
mouseEventArguments[0] = 'mouseenter';
mouseEventArguments[7] =
testSlider.ticks[1].offsetLeft + testSlider.sliderElem.offsetLeft; // clientX
mouseenter.initMouseEvent.apply(mouseenter, mouseEventArguments);
var mouseleave = document.createEvent('MouseEvent');
mouseEventArguments[0] = 'mouseleave';
mouseEventArguments[7] = testSlider.sliderElem.offsetLeft + bigOffset;
mouseleave.initMouseEvent.apply(mouseleave, mouseEventArguments);
testSlider.ticks[1].addEventListener('mouseleave', function() {
isTooltipVisible = $('#mySlider').find('.tooltip.tooltip-main').hasClass('in');
expect(isTooltipVisible).toBe(true);
done();
});
testSlider.ticks[1].dispatchEvent(mouseenter);
testSlider.ticks[1].dispatchEvent(mouseleave);
});
});
afterEach(function() {
if(testSlider) {
if(testSlider instanceof Slider) { testSlider.destroy(); }
testSlider = null;
}
});
});
/**
* The mouse navigation tests are based on the following slider properties:
*
* initial value: 3 or [3, 7]
* ticks: [0, 3, 5, 7, 10]
* step: 1
*
* When the `ticks_tooltip` option is set to `true`, hovering over the ticks or handles
* should show the tooltip above it with the value of the tick/handle.
*
* The test logic for sliders:
* 1. Hover over the 1st tick
* 2. Check if the tooltip is positioned correctly (left, top, right)
* 3. Check if the tooltip should be showing
* 4. Check if the tooltip contains the correct value
* 5. Check if the slider value(s) haven't changed
*
*/
describe("`ticks_tooltip: true` mouse navigation test cases", function() {
var initialValue = 3;
var initialRangeValues = [3, 7];
var tickValues = [0, 3, 5, 7, 10];
var stepValue = 1;
var orientations = ['horizontal', 'vertical'];
var reversed = [false, true];
var sliderTypes = ['single', 'range'];
var rtl = [false, true];
var testCases = [];
var mouseEventArguments;
function calcMouseEventCoords(element) {
var elementBB = element.getBoundingClientRect();
return {
clientX: elementBB.left,
clientY: elementBB.top
};
}
function createMouseEvent(type, clientX, clientY) {
var mouseEvent = document.createEvent('MouseEvent');
mouseEventArguments[0] = type;
mouseEventArguments[7] = clientX;
mouseEventArguments[8] = clientY;
mouseEvent.initMouseEvent.apply(mouseEvent, mouseEventArguments);
return mouseEvent;
}
beforeEach(function() {
// Set up default set of mouse event arguments
mouseEventArguments = [
'mousemove', // type
true, // canBubble
true, // cancelable
document, // view,
0, // detail
0, // screenX
0, // screenY
undefined, // clientX
undefined, // clientY,
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey,
0, // button
null // relatedTarget
];
});
sliderTypes.forEach(function(sliderType) {
orientations.forEach(function(orientation) {
rtl.forEach(function(isRTL) {
reversed.forEach(function(isReversed) {
var isHorizontal = orientation === 'horizontal';
var isVertical = orientation === 'vertical';
var isRange = sliderType === 'range';
var whichStyle;
if (isHorizontal) {
if (isRTL) {
whichStyle = 'right';
}
else {
whichStyle = 'left';
}
}
else if (isVertical) {
whichStyle = 'top';
}
testCases.push({
value: isRange ? initialRangeValues : initialValue,
step: stepValue,
range: isRange,
orientation: orientation,
reversed: isReversed,
rtl: 'auto',
isRTL: isRTL,
inputId: isRTL ? 'rtlSlider' : 'testSlider1',
expectedValue: isRange ? initialRangeValues : initialValue,
stylePos: whichStyle
});
});
});
});
});
testCases.forEach(function(testCase) {
describe("range=" + testCase.range + ", orientation=" + testCase.orientation +
", rtl=" + testCase.isRTL + ", reversed=" + testCase.reversed, function() {
var $testSlider;
var sliderElem;
var $handle1;
var $handle2;
var $ticks;
var sliderId;
var sliderOptions;
var $tooltip;
var $tooltipInner;
var lastTickIndex;
var mouseEventType = 'mouseenter';
beforeEach(function() {
sliderId = testCase.range ? 'myRangeSlider' : 'mySlider';
sliderOptions = {
id: sliderId,
step: testCase.step,
orientation: testCase.orientation,
value: testCase.value,
range: testCase.range,
reversed: testCase.reversed,
rtl: 'auto',
ticks: tickValues,
ticks_tooltip: true
};
$testSlider = $('#'+testCase.inputId).slider(sliderOptions);
sliderElem = $('#'+sliderId)[0];
$ticks = $(sliderElem).find('.slider-tick');
$handle1 = $(sliderElem).find('.slider-handle:first');
$handle2 = $(sliderElem).find('.slider-handle:last');
$tooltip = $(sliderElem).find('.tooltip.tooltip-main');
$tooltipInner = $tooltip.find('.tooltip-inner');
lastTickIndex = sliderOptions.ticks.length - 1;
});
afterEach(function() {
// Clean up any associated event listeners
$ticks = null;
$handle1 = null;
$handle2 = null;
if ($testSlider) {
$testSlider.slider('destroy');
$testSlider = null;
}
});
it("Should position the tooltip correctly", function(done) {
$ticks.each(function(index, tickElem) {
var coords = calcMouseEventCoords(tickElem);
var tickCallback = function() {
// Check position
expect($tooltip.css(testCase.stylePos)).toBe($(this).css(testCase.stylePos));
if (index === lastTickIndex) {
done();
}
};
// Set up listener and dispatch event
this.addEventListener(mouseEventType, tickCallback, false);
this.dispatchEvent(createMouseEvent(mouseEventType, coords.clientX, coords.clientY));
});
});
it("Should show the tooltip", function(done) {
$ticks.each(function(index, tickElem) {
var coords = calcMouseEventCoords(tickElem);
var tickCallback = function() {
// Check that tooltip shows
expect($tooltip.hasClass('in')).toBe(true);
if (index === lastTickIndex) {
done();
}
};
this.addEventListener(mouseEventType, tickCallback, false);
this.dispatchEvent(createMouseEvent(mouseEventType, coords.clientX, coords.clientY));
});
});
it("Should not show the tooltip", function(done) {
var bigOffset = 100000;
$ticks.each(function(index, tickElem) {
var coords = calcMouseEventCoords(tickElem);
var tickCallback = function() {
// Check that tooltip shows
expect($tooltip.hasClass('in')).toBe(false);
if (index === lastTickIndex) {
done();
}
};
this.addEventListener('mouseleave', tickCallback, false);
this.dispatchEvent(createMouseEvent('mouseleave', coords.clientX + bigOffset, coords.clientY));
});
});
it("Should contain the correct value for the tooltip", function(done) {
$ticks.each(function(index, tickElem) {
var coords = calcMouseEventCoords(tickElem);
var tickCallback = function() {
// Check value of tooltip
expect($tooltipInner.text()).toBe(''+sliderOptions.ticks[index]);
if (index === lastTickIndex) {
done();
}
};
this.addEventListener(mouseEventType, tickCallback, false);
this.dispatchEvent(createMouseEvent(mouseEventType, coords.clientX, coords.clientY));
});
});
it("Should not modify the value(s) of the slider when displaying the tooltip", function(done) {
$ticks.each(function(index, tickElem) {
var coords = calcMouseEventCoords(tickElem);
var tickCallback = function() {
var value = $testSlider.slider('getValue');
// Check value of slider
expect(value).toEqual(testCase.expectedValue);
if (index === lastTickIndex) {
done();
}
};
this.addEventListener(mouseEventType, tickCallback, false);
this.dispatchEvent(createMouseEvent(mouseEventType, coords.clientX, coords.clientY));
});
});
describe("Test position and values of the tooltip when hovering over the handle(s)", function() {
if (testCase.range) {
it("Should position for the tooltip correctly (range)", function(done) {
var handleElems = [$handle1[0], $handle2[0]];
$.each(handleElems, function(index, handleElem) {
var coords = calcMouseEventCoords(handleElem, testCase.orientation);
var handleCallback = function() {
// Check position
expect($tooltip.css(testCase.stylePos)).toBe($(handleElem).css(testCase.stylePos));
if (index === 1) {
done();
}
};
handleElem.addEventListener(mouseEventType, handleCallback, false);
handleElem.dispatchEvent(createMouseEvent(mouseEventType, coords.clientX, coords.clientY));
});
});
it("Should contain the correct values for the tooltip (range)", function(done) {
var handleElems = [$handle1[0], $handle2[0]];
$.each(handleElems, function(index, handleElem) {
var coords = calcMouseEventCoords(handleElem, testCase.orientation);
var handleCallback = function() {
// Check value of tooltip
expect($tooltipInner.text()).toBe(''+testCase.expectedValue[index]);
if (index === 1) {
done();
}
};
handleElem.addEventListener(mouseEventType, handleCallback, false);
handleElem.dispatchEvent(createMouseEvent(mouseEventType, coords.clientX, coords.clientY));
});
});
}
else {
it("Should position for the tooltip correctly (single)", function(done) {
var handleElem = $handle1[0];
var coords = calcMouseEventCoords(handleElem, testCase.orientation);
var handleCallback = function() {
// Check position
expect($tooltip.css(testCase.stylePos)).toBe($(handleElem).css(testCase.stylePos));
done();
};
handleElem.addEventListener(mouseEventType, handleCallback, false);
handleElem.dispatchEvent(createMouseEvent(mouseEventType, coords.clientX, coords.clientY));
});
it("Should contain the correct value for the tooltip (single)", function(done) {
var handleElem = $handle1[0];
var coords = calcMouseEventCoords(handleElem, testCase.orientation);
var handleCallback = function() {
// Check value of tooltip
expect($tooltipInner.text()).toBe(''+testCase.expectedValue);
done();
};
handleElem.addEventListener(mouseEventType, handleCallback, false);
handleElem.dispatchEvent(createMouseEvent(mouseEventType, coords.clientX, coords.clientY));
});
}
});
});
});
});

View File

@@ -0,0 +1,194 @@
/*
*************************
tooltip_position Option Test
*************************
*/
describe("'tooltip_position' Option tests", function() {
var testSlider;
afterEach(function() {
if(testSlider) {
testSlider.destroy();
testSlider = null;
}
});
describe("vertical slider tests", function() {
it("should be aligned to the left of the handle if set to 'left'", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5,
tooltip_position: "left",
orientation: "vertical"
});
// Extract needed references/values
var mainTooltipHasClassLeft = testSlider.tooltip.classList.contains("left");
// Assert
expect(mainTooltipHasClassLeft).toBeTruthy();
expect(testSlider.tooltip.style.right).toBe("100%");
});
it("should be aligned to the right of the handle if set to 'right'", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5,
tooltip_position: "right",
orientation: "vertical"
});
// Extract needed references/values
var mainTooltipHasClassRight = testSlider.tooltip.classList.contains("right");
// Assert
expect(mainTooltipHasClassRight).toBeTruthy();
expect(testSlider.tooltip.style.left).toBe("100%");
});
it("should default to 'right' if tooltip_position set to 'top'", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5,
tooltip_position: "top",
orientation: "vertical"
});
// Extract needed references/values
var mainTooltipHasClassRight = testSlider.tooltip.classList.contains("right");
// Assert
expect(mainTooltipHasClassRight).toBeTruthy();
expect(testSlider.tooltip.style.left).toBe("100%");
});
it("should default to 'right' if tooltip_position set to 'bottom'", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5,
tooltip_position: "bottom",
orientation: "vertical"
});
// Extract needed references/values
var mainTooltipHasClassRight = testSlider.tooltip.classList.contains("right");
// Assert
expect(mainTooltipHasClassRight).toBeTruthy();
expect(testSlider.tooltip.style.left).toBe("100%");
});
});
describe("horizontal slider tests", function() {
it("should be aligned above the handle if set to 'top'", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5,
tooltip_position: "top",
orientation: "horizontal"
});
// Extract needed references/values
var mainTooltipHasClassTop = testSlider.tooltip.classList.contains("top");
// Assert
expect(mainTooltipHasClassTop).toBeTruthy();
expect(testSlider.tooltip.style.top).toBe("");
});
it("should be aligned below the handle if set to 'bottom'", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5,
tooltip_position: "bottom",
orientation: "horizontal"
});
// Extract needed references/values
var mainTooltipHasClassTop = testSlider.tooltip.classList.contains("bottom");
// Assert
expect(mainTooltipHasClassTop).toBeTruthy();
expect(testSlider.tooltip.style.top).toBe("22px");
});
it("should be aligned below the handle if set to 'bottom' for range", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 20,
value: [0, 10],
range: true,
tooltip_position: "bottom",
orientation: "horizontal"
});
// Extract needed references/values
var mainTooltipHasClassTopMin = testSlider.tooltip_min.classList.contains("bottom");
var mainTooltipHasClassTopMax = testSlider.tooltip_max.classList.contains("bottom");
// Assert
expect(mainTooltipHasClassTopMin).toBeTruthy();
expect(mainTooltipHasClassTopMax).toBeTruthy();
expect(testSlider.tooltip_min.style.top).toBe("22px");
expect(testSlider.tooltip_max.style.top).toBe("22px");
});
it("should default to 'top' if tooltip_position set to 'left'", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5,
tooltip_position: "left",
orientation: "horizontal"
});
// Extract needed references/values
var mainTooltipHasClassTop = testSlider.tooltip.classList.contains("top");
// Assert
expect(mainTooltipHasClassTop).toBeTruthy();
expect(testSlider.tooltip.style.top).toBe("");
});
it("should default to 'top' if tooltip_position set to 'right'", function() {
// Create slider
testSlider = new Slider("#testSlider1", {
min: 0,
max: 10,
value: 5,
tooltip_position: "right",
orientation: "horizontal"
});
// Extract needed references/values
var mainTooltipHasClassTop = testSlider.tooltip.classList.contains("top");
// Assert
expect(mainTooltipHasClassTop).toBeTruthy();
expect(testSlider.tooltip.style.top).toBe("");
});
});
});

View File

@@ -0,0 +1,71 @@
/*
*************************
tooltip_split Option Test
*************************
This spec tests if tooltip_main, tooltip_min and tooltip_max
behave correctly when tooltip_split option is set to true or false.
*/
describe("'tooltip_split' Option tests", function() {
var testSlider, sliderId = "tooltipedSlider",
$slider, $tooltipMain, $tooltipMin, $tooltipMax,
sliderOptions = {id: sliderId, value: [0, 10], tooltip: "always"}; // for the sake of testing, always display the tooltip
describe("When 'tooltip_split' is false", function() {
beforeEach(function() {
testSlider = $("#testSlider1").slider($.extend(sliderOptions, {tooltip_split: false}));
$slider = $("#"+sliderId);
$tooltipMain = $slider.find(".tooltip-main");
$tooltipMin = $slider.find(".tooltip-min");
$tooltipMax = $slider.find(".tooltip-max");
});
it("should have `tooltip-main` displayed with `in` class", function() {
expect($tooltipMain.css("display")).not.toBe("none");
expect($tooltipMain.hasClass("in")).toBeTruthy();
});
it("should have `tooltip-min, tooltip-max` not displayed", function() {
expect($tooltipMin.css("display")).toBe("none");
expect($tooltipMin.hasClass("in")).toBeFalsy();
expect($tooltipMax.css("display")).toBe("none");
expect($tooltipMax.hasClass("in")).toBeFalsy();
});
});
describe("When 'tooltip_split' is true", function() {
beforeEach(function() {
testSlider = $("#testSlider1").slider($.extend(sliderOptions, {tooltip_split: true}));
$slider = $("#"+sliderId);
$tooltipMain = $slider.find(".tooltip-main");
$tooltipMin = $slider.find(".tooltip-min");
$tooltipMax = $slider.find(".tooltip-max");
});
it("should have `tooltip-min, tooltip-max` displayed with `in` class", function() {
expect($tooltipMin.css("display")).not.toBe("none");
expect($tooltipMin.hasClass("in")).toBeTruthy();
expect($tooltipMax.css("display")).not.toBe("none");
expect($tooltipMax.hasClass("in")).toBeTruthy();
});
it("should have `tooltip-main` not displayed", function() {
expect($tooltipMain.css("display")).toBe("none");
expect($tooltipMain.hasClass("in")).toBeFalsy();
});
it("should be aligned above the handle on init if set to 'top'", function() {
expect($tooltipMin.hasClass("top")).toBeTruthy();
expect($tooltipMax.hasClass("top")).toBeTruthy();
});
});
afterEach(function() {
if(testSlider) {
testSlider.slider('destroy');
testSlider = null;
}
});
});

View File

@@ -0,0 +1,571 @@
/* The following functions are taken and slightly modified from mock-phantom-touch-events.
*
* The original mock-phantom-touch-events can be found at https://github.com/gardr/mock-phantom-touch-events
*
* mock-phantom-touch-events is licensed under:
*
* The MIT License (MIT)
* Copyright (c) 2013 FINN.no AS
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
/*
list can be either [[x, y], [x, y]] or [x, y]
*/
function createTouchList(target, list) {
if (Array.isArray(list) && list[0] && !Array.isArray(list[0])) {
list = [list];
}
list = list.map(function (entry, index) {
var x = entry[0], y = entry[1], id = entry[2] ? entry[2] : index + 1;
return createTouch(x, y, target, id);
});
return document.createTouchList.apply(document, list);
}
function createTouch(x, y, target, id) {
return document.createTouch(window, target,
id || 1, //identifier
x, //pageX / clientX
y, //pageY / clientY
x, //screenX
y //screenY
);
}
function initTouchEvent(touchEvent, type, touches) {
var touch1 = touches[0];
return touchEvent.initTouchEvent(
touches, //touches
touches, //targetTouches
touches, //changedTouches
type, //type
window, //view
touch1.screenX, //screenX
touch1.screenY, //screenY
touch1.clientX, //clientX
touch1.clientY, //clientY
false, //ctrlKey
false, //altKey
false, //shiftKey
false //metaKey
);
}
function createTouchEvent(elem, type, touches) {
var touchEvent = document.createEvent('TouchEvent');
if (Array.isArray(touches)) {
touches = createTouchList(elem, touches);
}
initTouchEvent(touchEvent, type, touches);
return touchEvent;
}
function calcTouchEventCoords(element) {
var elementBB = element.getBoundingClientRect();
return {
x: elementBB.left,
y: elementBB.top
};
}
describe("Touch Capable Tests", function() {
var touchStart;
var touchMove;
var touchEnd;
var $testSlider;
var sliderInst;
var inputId;
var sliderId;
var sliderOptions;
beforeEach(function() {
inputId = 'testSlider1';
sliderId = 'mySlider';
sliderOptions = {
id: sliderId,
step: 1,
value: 5,
ticks: [0, 3, 5, 7, 10]
};
// Enable touch
window.ontouchstart = true;
});
afterEach(function() {
window.ontouchstart = null;
if ($testSlider) {
$testSlider.slider('destroy');
$testSlider = null;
}
});
describe("single slider", function() {
beforeEach(function() {
// Initialize the slider
$testSlider = $('#' + inputId).slider(sliderOptions);
// Get slider instance
sliderInst = $testSlider.data('slider');
});
// index= [0 1 2 3 4]
// ticks= [0 3 5 7 10]
it("should slide the handle to the left from 5 to 3", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
var value = $testSlider.slider('getValue');
expect(value).toBe(3);
done();
});
var tick = sliderInst.ticks[2]; // 5
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[1]; // 3
coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
it("should slide the handle to the right from 5 to 7", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
var value = $testSlider.slider('getValue');
expect(value).toBe(7);
done();
});
var tick = sliderInst.ticks[2]; // 5
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[3]; // 7
coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
});
describe("single, vertical slider", function() {
beforeEach(function() {
// Initialize the slider
sliderOptions.orientation = 'vertical';
$testSlider = $('#' + inputId).slider(sliderOptions);
// Get slider instance
sliderInst = $testSlider.data('slider');
});
// index= [0 1 2 3 4]
// ticks= [0 3 5 7 10]
it("should slide the handle to the top from 5 to 3", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
var value = $testSlider.slider('getValue');
expect(value).toBe(3);
done();
});
var tick = sliderInst.ticks[2]; // 5
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x, sliderCoords.y + tick.offsetTop];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[1]; // 3
coords = [sliderCoords.x, sliderCoords.y + tick.offsetTop];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
it("should slide the handle to the bottom from 5 to 7", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
var value = $testSlider.slider('getValue');
expect(value).toBe(7);
done();
});
var tick = sliderInst.ticks[2]; // 5
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x, sliderCoords.y + tick.offsetTop];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[3]; // 7
coords = [sliderCoords.x, sliderCoords.y + tick.offsetTop];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
});
describe("range slider", function() {
beforeEach(function() {
sliderOptions.range = true;
sliderOptions.value = [3, 7];
// Initialize the slider
$testSlider = $('#' + inputId).slider(sliderOptions);
// Get slider instance
sliderInst = $testSlider.data('slider');
});
// index= [0 1 2 3 4]
// ticks= [0 3 5 7 10]
it("should slide the first handle to the left from 3 to 0", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
var value = $testSlider.slider('getValue');
expect(value).toEqual([0, 7]);
done();
});
var tick = sliderInst.ticks[1]; // 3
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[0]; // 0
coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
it("should slide the second handle to the right from 7 to 10", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
var value = $testSlider.slider('getValue');
expect(value).toEqual([3, 10]);
done();
});
var tick = sliderInst.ticks[3]; // 7
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[4]; // 10
coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
});
describe("range, vertical slider", function() {
beforeEach(function() {
sliderOptions.range = true;
sliderOptions.value = [3, 7];
sliderOptions.orientation = 'vertical';
// Initialize the slider
$testSlider = $('#' + inputId).slider(sliderOptions);
// Get slider instance
sliderInst = $testSlider.data('slider');
});
// index= [0 1 2 3 4]
// ticks= [0 3 5 7 10]
it("should slide the first handle to the top from 3 to 0", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
var value = $testSlider.slider('getValue');
expect(value).toEqual([0, 7]);
done();
});
var tick = sliderInst.ticks[1]; // 3
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x, sliderCoords.y + tick.offsetTop];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[0]; // 0
coords = [sliderCoords.x, sliderCoords.y + tick.offsetTop];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
it("should slide the second handle to the bottom from 7 to 10", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
var value = $testSlider.slider('getValue');
expect(value).toEqual([3, 10]);
done();
});
var tick = sliderInst.ticks[3]; // 7
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x, sliderCoords.y + tick.offsetTop];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[4]; // 10
coords = [sliderCoords.x, sliderCoords.y + tick.offsetTop];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
});
describe("Tooltip tests", function() {
var $tooltip;
describe("single slider", function() {
beforeEach(function() {
// Initialize the slider
$testSlider = $('#' + inputId).slider(sliderOptions);
// Get slider instance
sliderInst = $testSlider.data('slider');
});
// index= [0 1 2 3 4]
// ticks= [0 3 5 7 10]
it("should show the tooltip when touching the slider at value 5", function(done) {
var sliderElem = $testSlider.slider('getElement');
$tooltip = $(sliderElem).find('.tooltip.tooltip-main');
/* Note: You can't use $testSlider.on('slideStart', function() {}) because jQuery
* maintains its own list of event handlers and you may get unexpected results
* when you add event handlers using $.on() versus DOM.addEventListener()
* as they are called in a different order.
*
* The browser will call the event handlers registered with addEventListener()
* in the order in which they are registered. For example, you'll get the following
* execution order when listening for "touchstart" events.
*
* 1) _touchstart()
* 2) _showTooltip()
* 3) your event handler here
*/
sliderElem.addEventListener('touchstart', function() {
expect($tooltip.hasClass('in')).toBe(true);
}, false);
$testSlider.on('slideStop', function() {
expect($tooltip.hasClass('in')).toBe(false);
done();
});
var tick = sliderInst.ticks[2]; // 5
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchEnd);
});
});
describe("range slider", function() {
var touchStart2;
beforeEach(function() {
sliderOptions.range = true;
sliderOptions.value = [3, 7];
// Initialize the slider
$testSlider = $('#' + inputId).slider(sliderOptions);
// Get slider instance
sliderInst = $testSlider.data('slider');
});
// index= [0 1 2 3 4]
// ticks= [0 3 5 7 10]
it("should show the tooltip when touching the slider at value 3 and 7", function(done) {
var sliderElem = $testSlider.slider('getElement');
$tooltip = $(sliderElem).find('.tooltip.tooltip-main');
sliderElem.addEventListener('touchstart', function() {
expect($tooltip.hasClass('in')).toBe(true);
}, false);
$testSlider.on('slideStop', function() {
expect($tooltip.hasClass('in')).toBe(false);
done();
});
var tick = sliderInst.ticks[1]; // 3
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
// For second handle
tick = sliderInst.ticks[3]; // 7
coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart2 = createTouchEvent(sliderElem, 'touchstart', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchStart2);
sliderElem.dispatchEvent(touchEnd);
});
});
});
describe("Scrolling tests", function() {
describe("horizontal sliding tests", function() {
var horzScrollDiv;
beforeEach(function() {
// Initialize the slider
$testSlider = $('#' + inputId).slider(sliderOptions);
// Get slider instance
sliderInst = $testSlider.data('slider');
horzScrollDiv = document.getElementById('horz-scroll-div');
});
// index= [0 1 2 3 4]
// ticks= [0 3 5 7 10]
it("should not scroll the div horizontally while sliding the slider", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
expect(horzScrollDiv.scrollLeft).toBe(0);
done();
});
var tick = sliderInst.ticks[2]; // 5
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[3]; // 7
coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
});
describe("vertical sliding tests", function() {
var vertScrollDiv;
beforeEach(function() {
sliderOptions.orientation = 'vertical';
// Initialize the slider
$testSlider = $('#' + inputId).slider(sliderOptions);
// Get slider instance
sliderInst = $testSlider.data('slider');
vertScrollDiv = document.getElementById('vert-scroll-div');
});
// index= [0 1 2 3 4]
// ticks= [0 3 5 7 10]
it("should not scroll the div vertically while sliding the slider", function(done) {
var sliderElem = $testSlider.slider('getElement');
$testSlider.on('slideStop', function() {
expect(vertScrollDiv.scrollTop).toBe(0);
done();
});
var tick = sliderInst.ticks[2]; // 5
var sliderCoords = calcTouchEventCoords(sliderElem);
var coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchStart = createTouchEvent(sliderElem, 'touchstart', coords);
tick = sliderInst.ticks[3]; // 7
coords = [sliderCoords.x + tick.offsetLeft, sliderCoords.y];
touchMove = createTouchEvent(sliderElem, 'touchmove', coords);
touchEnd = createTouchEvent(sliderElem, 'touchend', coords);
sliderElem.dispatchEvent(touchStart);
sliderElem.dispatchEvent(touchMove);
sliderElem.dispatchEvent(touchEnd);
});
});
});
});

View File

@@ -0,0 +1,33 @@
//--------------------------------------------------
//--------------------------------------------------
//-- Removes attached function from slider event --
//--------------------------------------------------
//--------------------------------------------------
describe("'off()' test", function() {
var testSlider, eventHandlerTriggered, mouse;
var onStart = function(){
eventHandlerTriggered = true;
};
beforeEach(function() {
eventHandlerTriggered = false;
mouse = document.createEvent('MouseEvents');
});
it("should properly unbind an event listener", function() {
testSlider = $("#testSlider1").slider();
testSlider.on('slideStart', onStart);
testSlider.off('slideStart', onStart);
testSlider.data('slider')._mousedown(mouse);
expect(eventHandlerTriggered).not.toBeTruthy();
});
});