Best JavaScript code snippet using playwright-internal
jquery-impromptu_spec.js
Source:jquery-impromptu_spec.js
1describe('jquery-impromptu', function() {2 // ====================================================================================3 // ====================================================================================4 describe('base structure', function(){5 // ====================================================================================6 describe('basic initialization', function() {7 beforeEach(function() { 8 $.fx.off = true; // for our testing lets turn off fx9 });10 afterEach(function() {11 $.prompt.close();12 });13 it('should be defined', function() {14 15 expect($.prompt).not.toBeUndefined();16 });17 it('should generate markup', function() {18 var expectedTitle = 'This is a title',19 expectedText = 'This is a test';20 $.prompt(expectedText, { title: expectedTitle });21 expect($('.jqibox')).toExist();22 expect($('.jqifade')).toExist();23 expect($('.jqi')).toExist();24 expect($('.jqi .jqititle')).toHaveText(expectedTitle);25 expect($('.jqi .jqimessage')).toHaveText(expectedText);26 });27 });28 // ====================================================================================29 describe('instance initialization', function() {30 var imp = new Impromptu();31 beforeEach(function() { 32 $.fx.off = true; // for our testing lets turn off fx33 });34 afterEach(function() {35 imp.close();36 });37 it('should be defined', function() {38 39 expect(imp).not.toBeUndefined();40 });41 it('should generate markup', function() {42 var expectedTitle = 'This is a title',43 expectedText = 'This is a test';44 imp.open(expectedText, { title: expectedTitle });45 expect($('.jqibox')).toExist();46 expect($('.jqifade')).toExist();47 expect($('.jqi')).toExist();48 expect($('.jqi .jqititle')).toHaveText(expectedTitle);49 expect($('.jqi .jqimessage')).toHaveText(expectedText);50 });51 });52 // ====================================================================================53 describe('button creation', function() {54 beforeEach(function() { 55 $.fx.off = true; // for our testing lets turn off fx56 });57 afterEach(function() {58 $.prompt.close();59 });60 it('should generate buttons from hash', function() {61 $.prompt('This is a test', {62 buttons: { Ok:true, Cancel:false }63 });64 var okBtn = $('button[name="jqi_state0_buttonOk"]'),65 cancelBtn = $('button[name="jqi_state0_buttonCancel"]');66 expect($('.jqibutton')).toHaveLength(2);67 expect(okBtn).toExist();68 expect(cancelBtn).toExist();69 expect(okBtn).toHaveText('Ok');70 expect(cancelBtn).toHaveText('Cancel');71 expect(okBtn).toHaveValue('true');72 expect(cancelBtn).toHaveValue('false');73 });74 it('should generate buttons from array', function() {75 $.prompt('This is a test', {76 buttons: [77 { title: 'Ok', value: true },78 { title: 'Cancel', value: false }79 ]80 });81 var okBtn = $('button[name="jqi_state0_buttonOk"]'),82 cancelBtn = $('button[name="jqi_state0_buttonCancel"]');83 expect($('.jqibutton')).toHaveLength(2);84 expect(okBtn).toExist();85 expect(cancelBtn).toExist();86 expect(okBtn).toHaveText('Ok');87 expect(cancelBtn).toHaveText('Cancel');88 expect(okBtn.val()).toBe('true');89 expect(cancelBtn.val()).toBe('false');90 });91 it('should add classes to buttons', function() {92 $.prompt('This is a test', {93 buttons: [94 { title: 'Ok', value: true, classes: ['ok1','ok2'] },95 { title: 'Cancel', value: false, classes: 'cancel1 cancel2' }96 ]97 });98 var okBtn = $('button[name="jqi_state0_buttonOk"]'),99 cancelBtn = $('button[name="jqi_state0_buttonCancel"]');100 expect(okBtn).toHaveClass('ok1');101 expect(okBtn).toHaveClass('ok2');102 expect(cancelBtn).toHaveClass('cancel1');103 expect(cancelBtn).toHaveClass('cancel2');104 });105 it('should add classes to buttons from classes obj', function() {106 $.prompt('This is a test', {107 buttons: [108 { title: 'Ok', value: true, classes: ['ok1','ok2'] },109 { title: 'Cancel', value: false, classes: 'cancel1 cancel2' }110 ],111 classes: { button: 'testclass' }112 });113 var okBtn = $('button[name="jqi_state0_buttonOk"]'),114 cancelBtn = $('button[name="jqi_state0_buttonCancel"]');115 expect(okBtn).toHaveClass('testclass');116 expect(cancelBtn).toHaveClass('testclass');117 });118 it('should default correct button', function() {119 $.prompt('This is a test', {120 buttons: [121 { title: 'Ok', value: 1 },122 { title: 'Cancel', value: 2 },123 { title: 'Another', value: 3 }124 ],125 focus: 1126 });127 var okBtn = $('button[name="jqi_state0_buttonOk"]'),128 cancelBtn = $('button[name="jqi_state0_buttonCancel"]'),129 anotherBtn = $('button[name="jqi_state0_buttonAnother"]');130 expect(okBtn).not.toHaveClass('jqidefaultbutton');131 expect(cancelBtn).toHaveClass('jqidefaultbutton');132 expect(anotherBtn).not.toHaveClass('jqidefaultbutton');133 });134 it('should default correct button when focus on an input', function() {135 $.prompt('This is a test <input type="text" id="testInput" />', {136 buttons: [137 { title: 'Ok', value: 1 },138 { title: 'Cancel', value: 2 },139 { title: 'Another', value: 3 }140 ],141 focus: '#testInput',142 defaultButton: 1143 });144 var okBtn = $('button[name="jqi_state0_buttonOk"]'),145 cancelBtn = $('button[name="jqi_state0_buttonCancel"]'),146 anotherBtn = $('button[name="jqi_state0_buttonAnother"]');147 expect(okBtn).not.toHaveClass('jqidefaultbutton');148 expect(cancelBtn).toHaveClass('jqidefaultbutton');149 expect(anotherBtn).not.toHaveClass('jqidefaultbutton');150 });151 });152 // ====================================================================================153 describe('state creation', function() {154 beforeEach(function() { 155 $.fx.off = true; // for our testing lets turn off fx156 });157 afterEach(function() {158 $.prompt.close();159 });160 it('should create a single state from string', function() {161 $.prompt('This is a test');162 163 expect($('.jqistate')).toExist();164 });165 it('should create states from hash', function() {166 var states = {167 s1: { html: 'state 1' },168 s2: { html: 'state 2' },169 s3: { html: 'state 3' }170 };171 $.prompt(states);172 173 expect($('.jqistate')).toHaveLength(3);174 expect($('.jqistate[data-jqi-name="s1"] .jqimessage')).toHaveText(states.s1.html);175 expect($('.jqistate[data-jqi-name="s2"] .jqimessage')).toHaveText(states.s2.html);176 expect($('.jqistate[data-jqi-name="s3"] .jqimessage')).toHaveText(states.s3.html);177 });178 it('should create states from array', function() {179 var states = [180 { html: 'state 1' },181 { html: 'state 2' },182 { html: 'state 3' }183 ];184 $.prompt(states);185 186 expect($('.jqistate')).toHaveLength(3);187 expect($('.jqistate[data-jqi-name="0"] .jqimessage')).toHaveText(states[0].html);188 expect($('.jqistate[data-jqi-name="1"] .jqimessage')).toHaveText(states[1].html);189 expect($('.jqistate[data-jqi-name="2"] .jqimessage')).toHaveText(states[2].html);190 });191 it('should show the first state automatically', function() {192 // we can't reliably determine which entry is the first with a hash, js doesn't preserve order193 var states = [194 { html: 'state 1' },195 { html: 'state 2' },196 { html: 'state 3' }197 ];198 $.prompt(states);199 expect($('.jqistate[data-jqi-name="0"]')).toHaveCss({display:'block'});200 expect($('.jqistate[data-jqi-name="1"]')).toHaveCss({display:'none'});201 expect($('.jqistate[data-jqi-name="2"]')).toHaveCss({display:'none'});202 });203 it('should name states properly when name specified', function() {204 var states = [205 { name: 's1', html: 'state 1' },206 { name: 's2', html: 'state 2' },207 { name: 's3', html: 'state 3' }208 ];209 $.prompt(states);210 211 expect($('.jqistate[data-jqi-name="s1"]')).toExist();212 expect($('.jqistate[data-jqi-name="s2"]')).toExist();213 expect($('.jqistate[data-jqi-name="s3"]')).toExist();214 });215 });216 }); // base structure217 // ====================================================================================218 // ====================================================================================219 describe('api methods', function() {220 var states = [221 { name: 's1', html: 'state 1' },222 { name: 's2', html: 'state 2' },223 { name: 's3', html: 'state 3' }224 ];225 beforeEach(function() { 226 $.fx.off = true; // for our testing lets turn off fx227 });228 afterEach(function() {229 $.prompt.close();230 });231 describe('static methods', function() {232 // ====================================================================================233 describe('$.prompt.setDefaults()', function() {234 it('should change the default values', function() {235 var origDefs = $.extend(true, {}, Impromptu.defaults),236 overrides = { prefix: 'myjqi', classes: { box: 'boxclass' } };237 238 $.prompt.setDefaults(overrides);239 expect(Impromptu.defaults.prefix).toBe(overrides.prefix);240 expect(Impromptu.defaults.classes.box).toBe(overrides.classes.box);241 expect(Impromptu.defaults.speed).toBe(origDefs.speed);242 Impromptu.defaults = origDefs;243 });244 });245 246 // ====================================================================================247 describe('$.prompt.setStateDefaults()', function() {248 it('should change the default state values', function() {249 var origDefs = $.extend(true, {}, Impromptu.defaults),250 overrides = { title: 'My Title', position: { width: 123 } };251 252 $.prompt.setStateDefaults(overrides);253 expect(Impromptu.defaults.state.title).toBe(overrides.title);254 expect(Impromptu.defaults.state.position.width).toBe(overrides.position.width);255 expect(Impromptu.defaults.state.focus).toBe(origDefs.state.focus);256 Impromptu.defaults = origDefs;257 });258 });259 });260 describe('instance methods', function() {261 // ====================================================================================262 describe('$.prompt.getBox()', function() {263 it('should return the box jquery object', function() {264 265 $.prompt('This is a test');266 var actualResult = $.prompt.getBox(),267 expectedResult = $('.jqibox');268 expect(actualResult[0]).toBe(expectedResult[0]);269 });270 });271 // ====================================================================================272 describe('$.prompt.getPrompt()', function() {273 it('should return the prompt jquery object', function() {274 275 $.prompt('This is a test');276 var actualResult = $.prompt.getPrompt(),277 expectedResult = $('.jqi');278 expect(actualResult[0]).toBe(expectedResult[0]);279 });280 });281 // ====================================================================================282 describe('$.prompt.getState()', function() {283 it('should return the state jquery object', function() {284 $.prompt(states);285 286 var actualResult = $.prompt.getState('s2'),287 expectedResult = $('.jqistate[data-jqi-name="s2"]');288 expect(actualResult[0]).toBe(expectedResult[0]);289 });290 });291 // ====================================================================================292 describe('$.prompt.getCurrentState()', function() {293 it('should return the current state jquery object', function() {294 $.prompt(states);295 296 var actualResult = $.prompt.getCurrentState(),297 expectedResult = $('.jqistate[data-jqi-name="s1"]');298 expect(actualResult[0]).toBe(expectedResult[0]);299 });300 it('should return the current state jquery object after a state change', function() {301 $.prompt(states);302 $.prompt.goToState('s2');303 var actualResult = $.prompt.getCurrentState(),304 expectedResult = $('.jqistate[data-jqi-name="s2"]');305 expect(actualResult[0]).toBe(expectedResult[0]);306 });307 });308 // ====================================================================================309 describe('$.prompt.getCurrentStateName()', function() {310 it('should return the current state name', function() {311 $.prompt(states);312 313 var actualResult = $.prompt.getCurrentStateName(),314 expectedResult = 's1';315 expect(actualResult).toBe(expectedResult);316 });317 it('should return the current state name after a state change', function() {318 $.prompt(states);319 $.prompt.goToState('s2');320 var actualResult = $.prompt.getCurrentStateName(),321 expectedResult = 's2';322 expect(actualResult).toBe(expectedResult);323 });324 });325 // ====================================================================================326 describe('$.prompt.goToState()', function() {327 it('should make the requested state visible', function() {328 $.prompt(states);329 330 $.prompt.goToState('s3');331 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'none'});332 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'none'});333 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'block'});334 });335 it('should do nothing if the state is not available', function() {336 $.prompt(states);337 338 $.prompt.goToState('s4');339 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'block'});340 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'none'});341 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'none'});342 });343 it('should handle substate option', function() {344 $.prompt(states);345 346 $.prompt.goToState('s2',true);347 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'block'});348 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'block'});349 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'none'});350 expect($('.jqistate[data-jqi-name="s2"]')).toHaveClass('jqisubstate');351 });352 });353 // ====================================================================================354 describe('$.prompt.nextState()', function() {355 it('should make the next state visible', function() {356 357 $.prompt(states);358 359 $.prompt.nextState();360 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'none'});361 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'block'});362 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'none'});363 });364 it('should do nothing if the state is not available', function() {365 $.prompt(states);366 367 $.prompt.goToState('s3');368 $.prompt.nextState();369 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'none'});370 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'none'});371 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'block'});372 });373 });374 // ====================================================================================375 describe('$.prompt.prevState()', function() {376 it('should make the previous state visible', function() {377 378 $.prompt(states);379 380 $.prompt.goToState('s3');381 $.prompt.prevState();382 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'none'});383 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'block'});384 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'none'});385 });386 it('should do nothing if the state is not available', function() {387 $.prompt(states);388 389 $.prompt.prevState();390 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'block'});391 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'none'});392 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'none'});393 });394 });395 // ====================================================================================396 describe('$.prompt.addState()', function() {397 it('should add a new state as the last state', function() {398 var newState = {399 name: 's4',400 title: 's4',401 html: 'testing s4',402 buttons: { Ok:true,Cancel:false}403 };404 $.prompt(states);405 406 var $stateobj = $.prompt.addState(newState.name, newState);407 // element created?408 expect($stateobj).toExist();409 // element in the right place?410 expect($stateobj.prev().data('jqi-name')).toBe('s3');411 // element visibility correct?412 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'block'});413 expect($stateobj).toHaveCss({display:'none'});414 // content generated ok?415 expect($stateobj.find('.jqimessage')).toHaveText(newState.html);416 expect($stateobj.find('.jqititle')).toHaveText(newState.title);417 expect($stateobj.find('.jqibutton')).toHaveLength(2);418 });419 it('should add a new state after specified state', function() {420 var newState = {421 name: 's4',422 title: 's4',423 html: 'testing s4',424 buttons: { Ok:true,Cancel:false}425 },426 afterState = 's2';427 $.prompt(states);428 429 var $stateobj = $.prompt.addState(newState.name, newState, afterState);430 expect($stateobj.prev().data('jqi-name')).toBe(afterState);431 });432 });433 // ====================================================================================434 describe('$.prompt.removeState()', function() {435 it('should remove the specified state', function() {436 437 $.prompt(states);438 439 $.prompt.removeState('s2');440 expect($('.jqistate[data-jqi-name="s2"]')).not.toExist();441 });442 443 it('should display requested state', function() {444 $.prompt(states);445 446 $.prompt.removeState('s1','s3');447 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'none'});448 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'block'});449 });450 451 it('should display next state', function() {452 $.prompt(states);453 454 $.prompt.removeState('s1');455 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'block'});456 expect($('.jqistate[data-jqi-name="s3"]')).toHaveCss({display:'none'});457 });458 459 it('should display previous state', function() {460 $.prompt(states);461 $.prompt.goToState('s3');462 $.prompt.removeState('s3');463 expect($('.jqistate[data-jqi-name="s1"]')).toHaveCss({display:'none'});464 expect($('.jqistate[data-jqi-name="s2"]')).toHaveCss({display:'block'});465 });466 467 });468 // ====================================================================================469 describe('$.prompt.disableStateButtons()', function() {470 it('should disable the buttons in a state', function() {471 472 $.prompt(states);473 474 $.prompt.disableStateButtons();475 expect($('.jqistate[data-jqi-name="s1"] button[disabled]').length).toBe(1);476 expect($('.jqistate[data-jqi-name="s2"] button[disabled]').length).toBe(0);477 });478 it('should disable the buttons in a specific state', function() {479 480 $.prompt(states);481 482 $.prompt.disableStateButtons('s2');483 expect($('.jqistate[data-jqi-name="s1"] button[disabled]').length).toBe(0);484 expect($('.jqistate[data-jqi-name="s2"] button[disabled]').length).toBe(1);485 });486 });487 // ====================================================================================488 describe('$.prompt.enbleStateButtons()', function() {489 it('should enable the buttons in a state', function() {490 491 $.prompt(states);492 493 $.prompt.disableStateButtons('s1');494 $.prompt.disableStateButtons('s2');495 $.prompt.enableStateButtons();496 expect($('.jqistate[data-jqi-name="s1"] button[disabled]').length).toBe(0);497 expect($('.jqistate[data-jqi-name="s2"] button[disabled]').length).toBe(1);498 });499 it('should enable the buttons in a specific state', function() {500 501 $.prompt(states);502 503 $.prompt.disableStateButtons('s1');504 $.prompt.disableStateButtons('s2');505 $.prompt.enableStateButtons('s2');506 expect($('.jqistate[data-jqi-name="s1"] button[disabled]').length).toBe(1);507 expect($('.jqistate[data-jqi-name="s2"] button[disabled]').length).toBe(0);508 });509 });510 // ====================================================================================511 describe('$.prompt.close()', function() {512 it('should close the prompt', function() {513 514 $.prompt(states);515 516 $.prompt.close();517 expect($('.jqibox')).not.toExist();518 });519 });520 }); // end instance methods521 }); // end api methods522 523 // ====================================================================================524 // ====================================================================================525 describe('api events', function() {526 var states = [527 { name: 's1', html: 'state 1', buttons: { next: true, cancel: false } },528 { name: 's2', html: 'state 2', buttons: { back: -1, cancel: 0, next: 1 } },529 { name: 's3', html: 'state 3', buttons: { done: true} }530 ];531 beforeEach(function() {532 $.fx.off = true; // for our testing lets turn off fx533 });534 afterEach(function() {535 $.prompt.close();536 $('.jqibox').remove();537 });538 // ====================================================================================539 describe('impromptu:loaded', function(){540 describe('running through jquery event binding', function(){541 var spyEventCalled;542 beforeEach(function(done){543 spyEventCalled = false;544 $('body').on('impromptu:loaded', '.jqibox', function(){ spyEventCalled=true; done(); });545 $.prompt(states);546 });547 it('should fire event', function(){548 expect(spyEventCalled).toBe(true);549 });550 });551 describe('passing loaded event through as option', function(){552 var spyEventCalled;553 beforeEach(function(done){554 spyEventCalled = false;555 $.prompt(states, { loaded: function(){ spyEventCalled = true; done(); } });556 });557 it('should allow event function as option parameter', function(){558 expect(spyEventCalled).toBe(true);559 });560 });561 });562 // ====================================================================================563 describe('impromptu:close', function(){564 describe('running through jquery event binding', function(){565 var spyEventCalled;566 beforeEach(function(done){567 spyEventCalled = false;568 $('body').on('impromptu:close', '.jqibox', function(){ spyEventCalled=true; done(); });569 $.prompt(states, {570 loaded: function(){571 $.prompt.close();572 }573 });574 });575 it('should fire event', function(){576 expect(spyEventCalled).toBe(true);577 });578 });579 describe('passing loaded event through as option', function(){580 var spyEventCalled;581 beforeEach(function(done){582 spyEventCalled = false;583 $.prompt(states, { 584 loaded: function(){ $.prompt.close(); },585 close: function(){ spyEventCalled = true; done(); }586 });587 });588 it('should allow event function as option parameter', function(){589 expect(spyEventCalled).toBe(true);590 });591 });592 });593 // ====================================================================================594 describe('impromptu:statechanging', function(){595 describe('running through jquery event binding', function(){596 var spyEventCalled;597 beforeEach(function(done){598 spyEventCalled = false;599 $('body').on('impromptu:statechanging', '.jqibox', function(){ spyEventCalled = true; done(); });600 $.prompt(states, {601 loaded: function(){602 $.prompt.goToState('s2');603 }604 });605 });606 it('should fire event', function(){607 expect(spyEventCalled).toBe(true);608 });609 });610 describe('passing loaded event through as option', function(){611 var spyEventCalled;612 beforeEach(function(done){613 spyEventCalled = false;614 $.prompt(states, { 615 loaded: function(){616 $.prompt.goToState('s2');617 },618 statechanging: function(){ spyEventCalled = true; done(); }619 });620 });621 it('should allow event function as option parameter', function(){622 expect(spyEventCalled).toBe(true);623 });624 });625 it('should allow preventDefault', function(){626 var spyEvent = spyOnEvent('body', 'impromptu:statechanging');627 $.prompt(states, { 628 loaded: function(){629 $.prompt.goToState('s2');630 },631 statechanging: function(e){632 e.preventDefault();633 }634 });635 636 expect(spyEvent).toHaveBeenTriggered();637 expect(spyEvent).toHaveBeenPrevented();638 });639 });640 // ====================================================================================641 describe('impromptu:statechanged', function(){642 describe('running through jquery event binding', function(){643 var spyEventCalled;644 beforeEach(function(done){645 spyEventCalled = false;646 $('body').on('impromptu:statechanged', '.jqibox', function(){ spyEventCalled = true; done(); });647 $.prompt(states, {648 loaded: function(){649 $.prompt.goToState('s2');650 }651 });652 });653 it('should fire event', function(){654 expect(spyEventCalled).toBe(true);655 });656 });657 describe('passing loaded event through as option', function(){658 var spyEventCalled;659 beforeEach(function(done){660 spyEventCalled = false;661 $.prompt(states, { 662 loaded: function(){663 $.prompt.goToState('s2');664 },665 statechanged: function(){ spyEventCalled = true; done(); }666 });667 });668 it('should allow event function as option parameter', function(){669 expect(spyEventCalled).toBe(true);670 });671 });672 });673 // ====================================================================================674 describe('impromptu:submit', function(){675 describe('running through jquery event binding', function(){676 var spyEventCalled;677 beforeEach(function(done){678 spyEventCalled = false;679 $('body').on('impromptu:submit', '.jqibox', function(){ spyEventCalled = true; done(); });680 $.prompt(states, {681 loaded: function(){682 $.prompt.getState('s1').find('.jqibutton:first').click();683 }684 });685 });686 it('should fire event', function(){687 expect(spyEventCalled).toBe(true);688 });689 });690 describe('passing submit event through as option if string message', function(){691 var spyEventCalled;692 beforeEach(function(done){693 spyEventCalled = false;694 $.prompt('Test message', { 695 loaded: function(){696 $('.jqibutton:first').click();697 },698 submit: function(){ spyEventCalled = true; done(); }699 });700 });701 it('should allow event function as option parameter', function(){702 expect(spyEventCalled).toBe(true);703 });704 });705 describe('should detect button clicked', function(){706 var btnClicked,707 msgReturned,708 formVals;709 beforeEach(function(done){710 $('body').on('impromptu:submit', '.jqibox', function(e,v,m,f){ 711 btnClicked = v; 712 msgReturned = m;713 formVals = f;714 done();715 });716 $.prompt(states, {717 loaded: function(){718 $.prompt.getState('s1').find('button[value="false"]').click();719 }720 });721 });722 it('should detect button', function(){723 expect(btnClicked).toBe(false);724 });725 it('should pass the state message', function(){726 expect(msgReturned.is('.jqimessage')).toBe(true);727 });728 });729 describe('verifying form values', function(){730 var tmpStates = [],731 btnClicked,732 msgReturned,733 formVals,734 expectedValues = {735 textInput: 'my text input',736 selectSingle: 'select single 3',737 selectMulti: ['select multi 2', 'select multi 3'],738 radioInput: 'my radio yes',739 chkInput: ['my chk no', 'my chk maybe'],740 textareaInput: 'my textarea val'741 };742 tmpStates[0] = $.extend({}, states[0]);743 tmpStates[0].html = '<input type="text" name="textInput" value="my text input" />'+744 '<select name="selectSingle"><option value="select single 1">select single 1</option><option value="select single 2">select single 2</option><option value="select single 3" selected>select single 3</option></select>'+745 '<select name="selectMulti" multiple><option value="select multi1">select multi 1</option><option value="select multi 2" selected>select multi 2</option><option value="select multi 3" selected>select multi 3</option></select>';746 tmpStates[1] = $.extend({}, states[1]);747 tmpStates[1].html = '<input type="radio" name="radioInput" value="my radio yes" checked />'+748 '<input type="radio" name="radioInput" value="my radio no" />'+749 '<input type="checkbox" name="chkInput" value="my chk no" checked />'+750 '<input type="checkbox" name="chkInput" value="my chk yes" />'+751 '<input type="checkbox" name="chkInput" value="my chk maybe" checked />';752 tmpStates[3] = $.extend({}, states[3]);753 tmpStates[3].html = '<textarea name="textareaInput">my textarea val</textarea>';754 beforeEach(function(done){755 $('body').on('impromptu:submit', '.jqibox', function(e,v,m,f){ 756 btnClicked = v; 757 msgReturned = m;758 formVals = f;759 done();760 });761 $.prompt(tmpStates, {762 loaded: function(){763 $.prompt.getState('s1').find('button[value="true"]').click();764 }765 });766 });767 it('should pass the correct form values', function(){768 expect(formVals).toEqual(expectedValues);769 });770 });771 });772 }); // end api events773 // ====================================================================================774 // ====================================================================================775 describe('native events', function() {776 var states = [777 { name: 's1', html: 'state 1', buttons: [{ title:'One', value: 1}, { title:'Two', value: 2}, { title:'Three', value: 3 }], focus: 1 },778 { name: 's2', html: 'state 2', buttons: { back: -1, cancel: 0, next: 1 } },779 { name: 's3', html: 'state 3', buttons: { done: true} }780 ];781 beforeEach(function() { 782 $.fx.off = true; // for our testing lets turn off fx783 });784 afterEach(function() {785 $.prompt.close();786 });787 // ====================================================================================788 describe('keydown', function(){789 describe('on fade when persistent option true', function(){790 beforeEach(function(done){791 $.prompt(states, { 792 loaded: function(){793 var e = $.Event('keydown');794 e.keyCode = 27;795 $.prompt.getBox().trigger(e);796 done();797 },798 persistent: true799 });800 });801 it('should not close prompt', function(){802 expect($('.jqi')).toExist();803 });804 });805 describe('on fade when persistent option false', function(){806 beforeEach(function(done){807 $.prompt(states, { 808 loaded: function(){809 var e = $.Event('keydown');810 e.keyCode = 27;811 $.prompt.getBox().trigger(e);812 done();813 },814 persistent: false815 });816 });817 it('should close prompt', function(){818 expect($('.jqi')).not.toExist();819 });820 });821 describe('enter key in prompt', function(){822 var buttonTriggered = null;823 beforeEach(function(done){824 $('body').on('impromptu:submit', function(e,v){825 buttonTriggered = v;826 done();827 });828 $.prompt(states, { 829 loaded: function(){830 var e = $.Event('keydown');831 e.keyCode = 13;832 $.prompt.getPrompt().trigger(e);833 }834 }); 835 });836 it('should trigger click on the correct button', function(){837 expect(buttonTriggered).toBe(2);838 });839 });840 841 });842 // ====================================================================================843 describe('click', function(){844 describe('fade click', function(){845 beforeEach(function(done){846 $.prompt(states, { 847 loaded: function(){848 var e = $.Event('click');849 $.prompt.getBox().trigger(e);850 done();851 },852 persistent: true853 });854 });855 it('should not close fade if persistent option true',function(){856 expect($('.jqi')).toExist();857 });858 });859 860 });861 });// end native events...
cropit_view.spec.js
Source:cropit_view.spec.js
1(function() {2 var dataKey, imageData, imageUrl;3 jasmine.getFixtures().fixturesPath = 'test/fixtures';4 dataKey = 'cropit';5 imageUrl = 'http://example.com/image.jpg';6 imageData = 'data:image/png;base64,image-data...';7 describe('Cropit View', function() {8 var $el, cropit;9 $el = null;10 cropit = null;11 describe('basic', function() {12 beforeEach(function() {13 loadFixtures('basic.html');14 return $el = $('.image-editor');15 });16 describe('init()', function() {17 it('sets preview size from options', function() {18 var $preview;19 $preview = $el.find('.cropit-image-preview');20 $preview.css({21 width: 1,22 height: 123 });24 expect($preview.width()).not.toBe(2);25 expect($preview.height()).not.toBe(2);26 $el.cropit({27 width: 2,28 height: 229 });30 expect($preview.width()).toBe(2);31 return expect($preview.height()).toBe(2);32 });33 it('sets preview background-repeat to no-repeat', function() {34 var $preview;35 $preview = $el.find('.cropit-image-preview');36 $preview.css({37 backgroundRepeat: 'repeat'38 });39 expect($preview.css('background-repeat')).not.toBe('no-repeat');40 $el.cropit();41 return expect($preview.css('background-repeat')).toBe('no-repeat');42 });43 it('sets min, max and step attributes on zoom slider', function() {44 var $zoomSlider;45 $zoomSlider = $el.find('input.cropit-image-zoom-input');46 $zoomSlider.attr({47 min: 2,48 max: 3,49 step: .550 });51 expect($zoomSlider.attr('min')).not.toBe('0');52 expect($zoomSlider.attr('max')).not.toBe('1');53 expect($zoomSlider.attr('step')).not.toBe('0.01');54 $el.cropit();55 expect($zoomSlider.attr('min')).toBe('0');56 expect($zoomSlider.attr('max')).toBe('1');57 return expect($zoomSlider.attr('step')).toBe('0.01');58 });59 return it('sets zoom slider to 0', function() {60 var $zoomSlider;61 $zoomSlider = $el.find('input.cropit-image-zoom-input');62 $zoomSlider.val(1);63 expect($zoomSlider.val()).not.toBe(0);64 $el.cropit();65 return expect(Number($zoomSlider.val())).toBe(0);66 });67 });68 describe('onFileChange()', function() {69 it('is invoked when file input changes', function() {70 var $fileInput;71 spyOn(Cropit.prototype, 'onFileChange');72 $el.cropit();73 $fileInput = $el.find('input.cropit-image-input');74 $fileInput.trigger('change');75 return expect(Cropit.prototype.onFileChange).toHaveBeenCalled();76 });77 return it('calls options.onFileChange()', function() {78 var onFileChangeCallback;79 onFileChangeCallback = jasmine.createSpy('onFileChange callback');80 $el.cropit({81 onFileChange: onFileChangeCallback82 });83 cropit = $el.data(dataKey);84 cropit.onFileChange();85 return expect(onFileChangeCallback).toHaveBeenCalled();86 });87 });88 describe('loadImage()', function() {89 return it('calls options.onImageLoading()', function() {90 var onImageLoadingCallback;91 onImageLoadingCallback = jasmine.createSpy('onImageLoading callback');92 $el.cropit({93 onImageLoading: onImageLoadingCallback94 });95 cropit = $el.data(dataKey);96 cropit.loadImage(imageData);97 return expect(onImageLoadingCallback).toHaveBeenCalled();98 });99 });100 describe('onImageLoaded()', function() {101 describe('with imageSrc', function() {102 beforeEach(function() {103 $el.cropit();104 cropit = $el.data(dataKey);105 return cropit.imageSrc = imageData;106 });107 it('sets preview background', function() {108 var $preview;109 $preview = $el.find('.cropit-image-preview');110 expect($preview).not.toHaveCss({111 backgroundImage: "url(" + imageData + ")"112 });113 cropit.onImageLoaded();114 return expect($preview).toHaveCss({115 backgroundImage: "url(" + imageData + ")"116 });117 });118 it('sets up zoomer', function() {119 spyOn(cropit.zoomer, 'setup');120 cropit.onImageLoaded();121 return expect(cropit.zoomer.setup).toHaveBeenCalled();122 });123 return it('updates zoom slider', function() {124 var $zoomSlider;125 $zoomSlider = $el.find('input.cropit-image-zoom-input');126 $zoomSlider.val(1);127 cropit.zoomer.getSliderPos = function() {128 return .5;129 };130 expect(Number($zoomSlider.val())).not.toBe(.5);131 cropit.onImageLoaded();132 return expect(Number($zoomSlider.val())).toBe(.5);133 });134 });135 return it('calls options.onImageLoaded()', function() {136 var onImageLoadedCallback;137 onImageLoadedCallback = jasmine.createSpy('onImageLoaded callback');138 $el.cropit({139 onImageLoaded: onImageLoadedCallback140 });141 cropit = $el.data(dataKey);142 cropit.onImageLoaded();143 return expect(onImageLoadedCallback).toHaveBeenCalled();144 });145 });146 describe('onImageError()', function() {147 return it('calls options.onImageError()', function() {148 var onImageError;149 onImageError = jasmine.createSpy('onImageLoaded callback');150 $el.cropit({151 onImageError: onImageError152 });153 cropit = $el.data(dataKey);154 cropit.onImageError();155 return expect(onImageError).toHaveBeenCalled();156 });157 });158 describe('onPreviewEvent()', function() {159 describe('mouse event', function() {160 it('is invoked on mousedown on preview', function() {161 var $preview;162 spyOn(Cropit.prototype, 'onPreviewEvent');163 $el.cropit();164 $preview = $el.find('.cropit-image-preview');165 $preview.trigger('mousedown');166 return expect(Cropit.prototype.onPreviewEvent).toHaveBeenCalled();167 });168 it('is invoked on mouseup on preview', function() {169 var $preview;170 spyOn(Cropit.prototype, 'onPreviewEvent');171 $el.cropit();172 $preview = $el.find('.cropit-image-preview');173 $preview.trigger('mouseup');174 return expect(Cropit.prototype.onPreviewEvent).toHaveBeenCalled();175 });176 it('is invoked on mouseleave on preview', function() {177 var $preview;178 spyOn(Cropit.prototype, 'onPreviewEvent');179 $el.cropit();180 $preview = $el.find('.cropit-image-preview');181 $preview.trigger('mouseleave');182 return expect(Cropit.prototype.onPreviewEvent).toHaveBeenCalled();183 });184 it('binds onMove() on mousedown', function() {185 var $preview;186 $el.cropit();187 cropit = $el.data(dataKey);188 cropit.imageLoaded = true;189 cropit.imageSize = {190 w: 8,191 h: 6192 };193 cropit.previewSize = {194 w: 2,195 h: 2196 };197 $preview = $el.find('.cropit-image-preview');198 spyOn(Cropit.prototype, 'onMove');199 cropit.onPreviewEvent({200 type: 'mousedown',201 stopPropagation: function() {}202 });203 $preview.trigger('mousemove');204 return expect(Cropit.prototype.onMove).toHaveBeenCalled();205 });206 return it('moves image by dragging', function() {207 $el.cropit();208 cropit = $el.data(dataKey);209 cropit.imageLoaded = true;210 cropit.imageSize = {211 w: 8,212 h: 6213 };214 cropit.previewSize = {215 w: 2,216 h: 2217 };218 cropit.setOffset({219 x: 0,220 y: 0221 });222 spyOn(cropit, 'setOffset');223 cropit.onPreviewEvent({224 type: 'mousedown',225 clientX: -1,226 clientY: -1,227 stopPropagation: function() {}228 });229 expect(cropit.setOffset).not.toHaveBeenCalled();230 cropit.onMove({231 type: 'mousemove',232 clientX: -3,233 clientY: -2,234 stopPropagation: function() {}235 });236 return expect(cropit.setOffset).toHaveBeenCalledWith({237 x: -2,238 y: -1239 });240 });241 });242 return describe('touch event', function() {243 it('is invoked on touchstart on preview', function() {244 var $preview;245 spyOn(Cropit.prototype, 'onPreviewEvent');246 $el.cropit();247 $preview = $el.find('.cropit-image-preview');248 $preview.trigger('touchstart');249 return expect(Cropit.prototype.onPreviewEvent).toHaveBeenCalled();250 });251 it('is invoked on touchend on preview', function() {252 var $preview;253 spyOn(Cropit.prototype, 'onPreviewEvent');254 $el.cropit();255 $preview = $el.find('.cropit-image-preview');256 $preview.trigger('touchend');257 return expect(Cropit.prototype.onPreviewEvent).toHaveBeenCalled();258 });259 it('is invoked on touchcancel on preview', function() {260 var $preview;261 spyOn(Cropit.prototype, 'onPreviewEvent');262 $el.cropit();263 $preview = $el.find('.cropit-image-preview');264 $preview.trigger('touchcancel');265 return expect(Cropit.prototype.onPreviewEvent).toHaveBeenCalled();266 });267 it('is invoked on touchleave on preview', function() {268 var $preview;269 spyOn(Cropit.prototype, 'onPreviewEvent');270 $el.cropit();271 $preview = $el.find('.cropit-image-preview');272 $preview.trigger('touchleave');273 return expect(Cropit.prototype.onPreviewEvent).toHaveBeenCalled();274 });275 it('binds onMove() on touchstart', function() {276 var $preview;277 $el.cropit();278 cropit = $el.data(dataKey);279 cropit.imageLoaded = true;280 cropit.imageSize = {281 w: 8,282 h: 6283 };284 cropit.previewSize = {285 w: 2,286 h: 2287 };288 $preview = $el.find('.cropit-image-preview');289 spyOn(Cropit.prototype, 'onMove');290 cropit.onPreviewEvent({291 type: 'touchstart',292 stopPropagation: function() {}293 });294 $preview.trigger('touchmove');295 return expect(Cropit.prototype.onMove).toHaveBeenCalled();296 });297 return it('moves image by dragging', function() {298 $el.cropit();299 cropit = $el.data(dataKey);300 cropit.imageLoaded = true;301 cropit.imageSize = {302 w: 8,303 h: 6304 };305 cropit.previewSize = {306 w: 2,307 h: 2308 };309 cropit.setOffset({310 x: 0,311 y: 0312 });313 spyOn(cropit, 'setOffset');314 cropit.onPreviewEvent({315 type: 'touchstart',316 clientX: -1,317 clientY: -1,318 stopPropagation: function() {}319 });320 expect(cropit.setOffset).not.toHaveBeenCalled();321 cropit.onMove({322 type: 'touchmove',323 clientX: -3,324 clientY: -2,325 stopPropagation: function() {}326 });327 return expect(cropit.setOffset).toHaveBeenCalledWith({328 x: -2,329 y: -1330 });331 });332 });333 });334 describe('setOffset()', function() {335 beforeEach(function() {336 $el.cropit();337 cropit = $el.data(dataKey);338 cropit.imageSize = {339 w: 8,340 h: 6341 };342 cropit.previewSize = {343 w: 2,344 h: 2345 };346 cropit.zoom = 1;347 return cropit.imageLoaded = true;348 });349 return it('moves preview image', function() {350 var $preview;351 $preview = $el.find('.cropit-image-preview');352 expect($preview).not.toHaveCss({353 backgroundPosition: '-1px -1px'354 });355 cropit.setOffset({356 x: -1,357 y: -1358 });359 return expect($preview).toHaveCss({360 backgroundPosition: '-1px -1px'361 });362 });363 });364 describe('onZoomSliderChange()', function() {365 it('is invoked mousemove on zoom slider', function() {366 var $zoomSlider;367 spyOn(Cropit.prototype, 'onZoomSliderChange');368 $el.cropit();369 $zoomSlider = $el.find('input.cropit-image-zoom-input');370 $zoomSlider.trigger('mousemove');371 return expect(Cropit.prototype.onZoomSliderChange).toHaveBeenCalled();372 });373 it('is invoked touchmove on zoom slider', function() {374 var $zoomSlider;375 spyOn(Cropit.prototype, 'onZoomSliderChange');376 $el.cropit();377 $zoomSlider = $el.find('input.cropit-image-zoom-input');378 $zoomSlider.trigger('touchmove');379 return expect(Cropit.prototype.onZoomSliderChange).toHaveBeenCalled();380 });381 it('is invoked change on zoom slider', function() {382 var $zoomSlider;383 spyOn(Cropit.prototype, 'onZoomSliderChange');384 $el.cropit();385 $zoomSlider = $el.find('input.cropit-image-zoom-input');386 $zoomSlider.trigger('change');387 return expect(Cropit.prototype.onZoomSliderChange).toHaveBeenCalled();388 });389 return describe('when invoked', function() {390 beforeEach(function() {391 $el.cropit();392 cropit = $el.data(dataKey);393 cropit.imageSize = {394 w: 8,395 h: 6396 };397 cropit.previewSize = {398 w: 2,399 h: 2400 };401 cropit.zoom = 1;402 cropit.imageLoaded = true;403 return cropit.setZoom = function() {};404 });405 it('updates zoomSliderPos', function() {406 var $zoomSlider;407 cropit.zoomSliderPos = 0;408 expect(cropit.zoomSliderPos).not.toBe(1);409 $zoomSlider = $el.find('input.cropit-image-zoom-input');410 $zoomSlider.val(1);411 cropit.onZoomSliderChange();412 return expect(cropit.zoomSliderPos).toBe(1);413 });414 return it('calls setZoom', function() {415 spyOn(cropit, 'setZoom');416 cropit.onZoomSliderChange();417 return expect(cropit.setZoom).toHaveBeenCalled();418 });419 });420 });421 return describe('setZoom()', function() {422 var $preview;423 $preview = null;424 beforeEach(function() {425 $el.cropit();426 cropit = $el.data(dataKey);427 cropit.imageSize = {428 w: 8,429 h: 12430 };431 cropit.previewSize = {432 w: 2,433 h: 2434 };435 cropit.offset = {436 x: 0,437 y: 0438 };439 cropit.zoom = .5;440 cropit.imageLoaded = true;441 cropit.zoomer.minZoom = .5;442 cropit.zoomer.maxZoom = 1;443 return $preview = $el.find('.cropit-image-preview');444 });445 it('keeps attributes when set to original zoom', function() {446 cropit.setZoom(.5);447 expect(cropit.zoom).toBe(.5);448 expect(cropit.offset).toEqual({449 x: 0,450 y: 0451 });452 expect($preview).toHaveCss({453 backgroundPosition: '0px 0px'454 });455 return expect($preview).toHaveCss({456 backgroundSize: '4px 6px'457 });458 });459 it('zooms preview image', function() {460 expect(cropit.zoom).not.toBe(1);461 expect(cropit.offset).not.toEqual({462 x: -1,463 y: -1464 });465 expect($preview).not.toHaveCss({466 backgroundPosition: '-1px -1px'467 });468 expect($preview).not.toHaveCss({469 backgroundSize: '8px 12px'470 });471 cropit.setZoom(1);472 expect(cropit.zoom).toBe(1);473 expect(cropit.offset).toEqual({474 x: -1,475 y: -1476 });477 expect($preview).toHaveCss({478 backgroundPosition: '-1px -1px'479 });480 return expect($preview).toHaveCss({481 backgroundSize: '8px 12px'482 });483 });484 return it('keeps zoom in proper range', function() {485 expect(cropit.zoom).not.toBe(1);486 expect(cropit.offset).not.toEqual({487 x: -1,488 y: -1489 });490 expect($preview).not.toHaveCss({491 backgroundPosition: '-1px -1px'492 });493 expect($preview).not.toHaveCss({494 backgroundSize: '8px 12px'495 });496 cropit.setZoom(1.5);497 expect(cropit.zoom).toBe(1);498 expect(cropit.offset).toEqual({499 x: -1,500 y: -1501 });502 expect($preview).toHaveCss({503 backgroundPosition: '-1px -1px'504 });505 return expect($preview).toHaveCss({506 backgroundSize: '8px 12px'507 });508 });509 });510 });511 return describe('with background image', function() {512 beforeEach(function() {513 loadFixtures('image-background.html');514 return $el = $('.image-editor');515 });516 describe('init()', function() {517 it('inserts background image', function() {518 var $imageBg;519 $el.cropit({520 imageBackground: true521 });522 $imageBg = $el.find('img.cropit-image-background');523 expect($imageBg).toBeInDOM();524 return expect($imageBg).toHaveCss({525 position: 'absolute'526 });527 });528 it('inserts background image container', function() {529 var $imageBgContainer;530 $el.cropit({531 imageBackground: true532 });533 $imageBgContainer = $el.find('.cropit-image-background-container');534 expect($imageBgContainer).toBeInDOM();535 return expect($imageBgContainer).toHaveCss({536 position: 'absolute'537 });538 });539 it('offsets background image when border is specified', function() {540 var $imageBgContainer, $preview;541 $el.cropit({542 imageBackground: true,543 imageBackgroundBorderWidth: [1, 2, 3, 4]544 });545 $preview = $el.find('.cropit-image-preview');546 $imageBgContainer = $el.find('.cropit-image-background-container');547 return expect($imageBgContainer).toHaveCss({548 left: '-4px',549 top: '-1px',550 width: "" + ($preview.width() + 2 + 4) + "px",551 height: "" + ($preview.height() + 1 + 3) + "px"552 });553 });554 return it('takes numeric background image border size to make uniform border size', function() {555 var $imageBgContainer, $preview;556 $el.cropit({557 imageBackground: true,558 imageBackgroundBorderWidth: 3559 });560 $preview = $el.find('.cropit-image-preview');561 $imageBgContainer = $el.find('.cropit-image-background-container');562 return expect($imageBgContainer).toHaveCss({563 left: '-3px',564 top: '-3px',565 width: "" + ($preview.width() + 2 * 3) + "px",566 height: "" + ($preview.height() + 2 * 3) + "px"567 });568 });569 });570 describe('onImageLoaded()', function() {571 return it('updates background image source', function() {572 var $imageBg;573 $el.cropit({574 imageBackground: true575 });576 cropit = $el.data(dataKey);577 cropit.imageSrc = imageData;578 $imageBg = $el.find('img.cropit-image-background');579 expect($imageBg).not.toHaveAttr('src', imageData);580 cropit.onImageLoaded();581 return expect($imageBg).toHaveAttr('src', imageData);582 });583 });584 describe('setOffset()', function() {585 it('updates background image position', function() {586 var $imageBg;587 $el.cropit({588 imageBackground: true589 });590 cropit = $el.data(dataKey);591 cropit.imageSize = {592 w: 8,593 h: 6594 };595 cropit.previewSize = {596 w: 2,597 h: 2598 };599 cropit.zoom = 1;600 $imageBg = $el.find('img.cropit-image-background');601 expect($imageBg).not.toHaveCss({602 left: '-1px',603 top: '-1px'604 });605 cropit.setOffset({606 x: -1,607 y: -1608 });609 return expect($imageBg).toHaveCss({610 left: '-1px',611 top: '-1px'612 });613 });614 return it('adds background image border size to background image offset', function() {615 var $imageBg;616 $el.cropit({617 imageBackground: true,618 imageBackgroundBorderWidth: 2619 });620 cropit = $el.data(dataKey);621 cropit.imageSize = {622 w: 8,623 h: 6624 };625 cropit.previewSize = {626 w: 2,627 h: 2628 };629 cropit.zoom = 1;630 $imageBg = $el.find('img.cropit-image-background');631 expect($imageBg).not.toHaveCss({632 left: '-1px',633 top: '-1px'634 });635 cropit.setOffset({636 x: -3,637 y: -3638 });639 return expect($imageBg).toHaveCss({640 left: '-1px',641 top: '-1px'642 });643 });644 });645 return describe('setZoom()', function() {646 return it('zooms background image', function() {647 var $imageBg;648 $el.cropit({649 imageBackground: true650 });651 cropit = $el.data(dataKey);652 cropit.imageSize = {653 w: 8,654 h: 12655 };656 cropit.previewSize = {657 w: 2,658 h: 2659 };660 cropit.offset = {661 x: 0,662 y: 0663 };664 cropit.zoom = .5;665 cropit.imageLoaded = true;666 cropit.zoomer.minZoom = .5;667 cropit.zoomer.maxZoom = 1;668 $imageBg = $el.find('img.cropit-image-background');669 expect($imageBg).not.toHaveCss({670 width: '8px',671 height: '12px'672 });673 cropit.setZoom(1);674 return expect($imageBg).toHaveCss({675 width: '8px',676 height: '12px'677 });678 });679 });680 });681 });...
formatting.js
Source:formatting.js
1'use strict';2describe('Formatting', function() {3 var testBookUrl = '/base/app/books/9780007441235', $container = null,4 fontSize = {5 unit: 18,6 default: 17 },8 lineHeight = {9 unit: 16,10 default: 1.211 },12 margin = {13 min : [9.8, 4, 6.5, 4],14 max: [9.8, 17.75, 6.5, 17.75],15 medium: [9.8, 11, 6.5, 11]16 },17 themes = {18 transparent : {19 background : 'transparent',20 title : '#666',21 color : '#000'22 },23 light : {24 background : '#f4f4f4',25 title : '#666',26 color : '#000'27 },28 dark : {29 background : '#000000',30 title : '#666',31 color : '#dddddd'32 },33 sepia : {34 background : '#ede7d5',35 title : '#666',36 color : '#181818'37 }38 },39 flags = {40 hasErrors: false41 },42 defaultArgs = {43 preferences: {44 transitionDuration: 045 },46 width: 200,47 height: 300,48 url: testBookUrl,49 listener: function(ev){50 switch(ev.code){51 case 6: // reader finished loading52 break;53 case 9: // reader missing a file54 case 10: // parsing failed55 case 11: // cfi generation error56 case 12: // cfi insertion57 case 13: // invalid argument58 case 14: // cannot add bookmark59 case 15: // bookmark already exists60 case 16: // cannot remove bookmark61 flags.hasErrors = true;62 break;63 }64 }65 };66 beforeEach(function(){67 flags.hasErrors = false;68 // making sure the reader has a valid container in the body69 $container = $('<div></div>').appendTo($('body'));70 });71 afterEach(function(){72 expect($container).toHaveReaderStructure();73 expect(flags.hasErrors).toBe(false);74 });75 describe('Font size', function() {76 it('should initialise the reader with the default font size', function(done) {77 READER.init($.extend({78 container: $container79 }, defaultArgs)).then(function(){80 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');81 expect($contents).toHaveCss({82 'font-size': (fontSize.default * fontSize.unit) + 'px'83 });84 done();85 });86 });87 it('should initialise the reader with the given font size', function(done) {88 var value = 2;89 READER.init($.extend(true, {90 container: $container,91 preferences: {92 fontSize: value93 }94 }, defaultArgs)).then(function(){95 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');96 expect($contents).toHaveCss({97 'font-size': (fontSize.unit * value) + 'px'98 });99 done();100 });101 });102 it('should apply font-size', function(done){103 var value = 1.5, value2 = 2.5;104 READER.init($.extend({105 container: $container106 }, defaultArgs)).then(function(){107 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');108 READER.setFontSize(value);109 expect($contents).toHaveCss({110 'font-size': (fontSize.unit * value) + 'px'111 });112 READER.setPreferences({113 fontSize: value2114 });115 expect($contents).toHaveCss({116 'font-size': (fontSize.unit * value2) + 'px'117 });118 done();119 });120 });121 it('should increase font size', function(done){122 var step = 0.1;123 READER.init($.extend(true, {124 container: $container,125 preferences: {126 fontSize: 1127 }128 }, defaultArgs)).then(function(){129 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');130 // calling increase font size twice131 READER.increaseFontSize();132 READER.increaseFontSize();133 var $test = $('<span></span>');134 $test.css('font-size', ((fontSize.default + 2 * step) * fontSize.unit) + 'px');135 expect($contents).toHaveCss({136 'font-size': Math.round((fontSize.default + 2 * step) * fontSize.unit) + 'px'137 });138 done();139 });140 });141 it('should decrease font size', function(done){142 var step = 0.1;143 READER.init($.extend(true, {144 container: $container,145 preferences: {146 fontSize: 1147 }148 }, defaultArgs)).then(function(){149 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');150 // calling increase font size twice151 READER.decreaseFontSize();152 expect($contents).toHaveCss({153 'font-size': Math.round((fontSize.default - step) * fontSize.unit) + 'px'154 });155 done();156 });157 });158 });159 describe('Line height', function() {160 it('should initialise the reader with the default line height', function(done) {161 READER.init($.extend({162 container: $container163 }, defaultArgs)).then(function(){164 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');165 var fontSize = parseInt($contents.css('fontSize'));166 expect($contents).toHaveCss({167 // line height appears to be computed as the floor value of the actual value168 'line-height': Math.floor(lineHeight.default * fontSize) + 'px'169 });170 done();171 });172 });173 it('should initialise the reader with the given line height', function(done) {174 var value = 2;175 READER.init($.extend(true, {176 container: $container,177 preferences: {178 lineHeight: value179 }180 }, defaultArgs)).then(function(){181 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');182 var fontSize = parseInt($contents.css('fontSize'));183 expect($contents).toHaveCss({184 'line-height': (fontSize * value) + 'px'185 });186 done();187 });188 });189 it('should apply line height', function(done){190 var value = 1.5, value2 = 2.5;191 READER.init($.extend(192 {container: $container},193 defaultArgs194 )).then(function(){195 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');196 READER.setLineHeight(value);197 fontSize = parseInt($contents.css('fontSize'));198 expect($contents).toHaveCss({199 'line-height': (fontSize * value) + 'px'200 });201 READER.setPreferences({202 lineHeight: value2203 });204 fontSize = parseInt($contents.css('fontSize'));205 expect($contents).toHaveCss({206 'line-height': (fontSize * value2) + 'px'207 });208 done();209 });210 });211 it('should increase line height', function(done){212 var step = 0.1;213 READER.init($.extend(true, {214 container: $container,215 preferences: {216 lineHeight: 2217 }218 }, defaultArgs)).then(function(){219 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');220 fontSize = parseInt($contents.css('fontSize'));221 // calling increase line height twice222 READER.increaseLineHeight();223 READER.increaseLineHeight();224 expect($contents).toHaveCss({225 'line-height': Math.round((2 + 2 * step) * fontSize) + 'px'226 });227 done();228 });229 });230 it('should decrease line height', function(done){231 var step = 0.1;232 READER.init($.extend(true, {233 container: $container,234 preferences: {235 lineHeight: 2236 }237 }, defaultArgs)).then(function(){238 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');239 fontSize = parseInt($contents.css('fontSize'));240 // calling increase font size twice241 READER.decreaseLineHeight();242 expect($contents).toHaveCss({243 'line-height': Math.round((2 - step) * fontSize) + 'px'244 });245 done();246 });247 });248 });249 describe('Font family', function() {250 it('should initialise the reader with the default font family', function(done) {251 READER.init($.extend({252 container: $container253 }, defaultArgs)).then(function(){254 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');255 expect($contents).toHaveCss({256 fontFamily: 'Arial'257 });258 done();259 });260 });261 it('should initialise the reader with the given line height', function(done) {262 var value = 'Helvetica';263 READER.init($.extend(true, {264 container: $container,265 preferences: {266 fontFamily: value267 }268 }, defaultArgs)).then(function(){269 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');270 expect($contents).toHaveCss({271 fontFamily: value272 });273 done();274 });275 });276 it('should apply font family', function(done){277 var value = 'Times New Roman', value2 = 'Comic Sans';278 READER.init($.extend(279 {container: $container},280 defaultArgs281 )).then(function(){282 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');283 READER.setFontFamily(value);284 expect($contents).toHaveCss({285 // it appears some fonts are considered plain strings http://stackoverflow.com/a/11903633286 fontFamily: value287 });288 READER.setPreferences({289 fontFamily: value2290 });291 expect($contents).toHaveCss({292 fontFamily: value2293 });294 done();295 });296 });297 });298 describe('Text align', function() {299 it('should initialise the reader with the default text align', function(done) {300 READER.init($.extend({container: $container}, defaultArgs)).then(function(){301 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');302 expect($contents).toHaveCss({303 textAlign: 'left'304 });305 done();306 });307 });308 it('should initialise the reader with the given text align', function(done) {309 var value = 'justify';310 READER.init($.extend(true, {311 container: $container,312 preferences: {313 textAlign: value314 }315 }, defaultArgs)).then(function(){316 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');317 expect($contents).toHaveCss({318 textAlign: value319 });320 done();321 });322 });323 it('should apply text align', function(done){324 var value = 'left', value2 = 'justify';325 READER.init($.extend(326 {container: $container},327 defaultArgs328 )).then(function(){329 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');330 READER.setTextAlign(value);331 expect($contents).toHaveCss({332 textAlign: value333 });334 READER.setPreferences({335 textAlign: value2336 });337 expect($contents).toHaveCss({338 textAlign: value2339 });340 done();341 });342 });343 });344 describe('Theme', function() {345 it('should initialise the reader with the default text align', function(done) {346 READER.init($.extend(347 {container: $container},348 defaultArgs349 )).then(function(){350 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');351 expect($container.find('iframe').contents().find('body')).toHaveCss({352 backgroundColor: 'rgb(255, 255, 255)'353 });354 expect($contents).toHaveCss({355 color: 'rgb(0, 0, 0)'356 });357 done();358 });359 });360 it('should initialise the reader with a predefined theme', function(done) {361 var value = 'dark';362 READER.init($.extend(true, {363 container: $container,364 preferences: {365 theme: value366 }367 }, defaultArgs)).then(function(){368 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');369 expect($container.find('iframe').contents().find('body')).toHaveCss({370 backgroundColor: themes.dark.background371 });372 expect($contents).toHaveCss({373 color: themes.dark.color374 });375 done();376 });377 });378 it('should initialise the reader with the given theme', function(done) {379 var value = {380 background : 'rgb(1, 2, 3)',381 title : '#666',382 color : 'rgb(10, 20, 30)'383 };384 READER.init($.extend(true, {385 container: $container,386 preferences: {387 theme: value388 }389 }, defaultArgs)).then(function(){390 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');391 expect($container.find('iframe').contents().find('body')).toHaveCss({392 backgroundColor: value.background393 });394 expect($contents).toHaveCss({395 color: value.color396 });397 done();398 });399 });400 it('should apply theme', function(done){401 var value = 'sepia', value2 = 'light';402 READER.init($.extend(403 {container: $container},404 defaultArgs405 )).then(function(){406 var $contents = $container.find('iframe').contents().find('#cpr-reader').find('span, p, em, div, strong, a');407 READER.setTheme(value);408 expect($container.find('iframe').contents().find('body')).toHaveCss({409 backgroundColor: themes.sepia.background410 });411 expect($contents).toHaveCss({412 color: themes.sepia.color413 });414 READER.setPreferences({415 theme: value2416 });417 expect($container.find('iframe').contents().find('body')).toHaveCss({418 backgroundColor: themes.light.background419 });420 expect($contents).toHaveCss({421 color: themes.light.color422 });423 done();424 });425 });426 });427 describe('Margin', function() {428 it('should initialise the reader with the default margins', function(done) {429 READER.init($.extend({430 container: $container,431 width: 200,432 height: 300433 }, defaultArgs)).then(function(){434 var $contents = $container.find('iframe').contents().find('#cpr-reader').parent();435 expect($contents).toHaveCss({436 // by default the margin is 11% of the reader width437 marginRight: Math.floor(margin.medium[1]/100 * 200) + 'px',438 marginLeft: Math.floor(margin.medium[3]/100 * 200) + 'px'439 });440 done();441 });442 });443 it('should initialise the reader with a predefined margin', function(done) {444 READER.init($.extend(true, {445 container: $container,446 width: 200,447 height: 300,448 preferences: {449 margin: 'min'450 }451 }, defaultArgs)).then(function(){452 var $contents = $container.find('iframe').contents().find('#cpr-reader').parent();453 expect($contents).toHaveCss({454 marginRight: Math.floor(margin.min[1]/100 * 200) + 'px',455 marginLeft: Math.floor(margin.min[3]/100 * 200) + 'px'456 });457 done();458 });459 });460 it('should initialise the reader with the given margin', function(done) {461 var value = [10,10,10,10];462 READER.init($.extend(true, {463 container: $container,464 width: 200,465 height: 300,466 preferences: {467 margin: value468 }469 }, defaultArgs)).then(function(){470 var $contents = $container.find('iframe').contents().find('#cpr-reader').parent();471 expect($contents).toHaveCss({472 marginRight: Math.floor(value[1]/100 * 200) + 'px',473 marginLeft: Math.floor(value[3]/100 * 200) + 'px'474 });475 done();476 });477 });478 it('should apply margin', function(done){479 var value = 'max', value2 = 'min';480 READER.init($.extend(481 {container: $container},482 defaultArgs483 )).then(function(){484 var $contents = $container.find('iframe').contents().find('#cpr-reader').parent();485 READER.setMargin(value);486 expect($contents).toHaveCss({487 marginRight: Math.floor(margin.max[1]/100 * 200) + 'px',488 marginLeft: Math.floor(margin.max[3]/100 * 200) + 'px'489 });490 READER.setPreferences({491 margin: value2492 });493 expect($contents).toHaveCss({494 marginRight: Math.floor(margin.min[1]/100 * 200) + 'px',495 marginLeft: Math.floor(margin.min[3]/100 * 200) + 'px'496 });497 done();498 });499 });500 });...
jquery.jcreate.spec.js
Source:jquery.jcreate.spec.js
1describe('jCreate', function() {2 var $container3 , style_red = {'display' : 'block', 'margin-top' : '10px', 'color' : 'rgb(255, 0, 0)'}4 , style_green = {'display' : 'block', 'margin-top' : '10px', 'color' : 'rgb(0, 255, 0)'}5 , style_blue = {'display' : 'block', 'margin-top' : '10px', 'color' : 'rgb(0, 0, 255)'}6 ;7 beforeEach(function ()8 {9 loadFixtures('container.html');10 $container = jQuery('#container');11 spyOn(console, 'info');12 // add 'create' event to container.13 $container.on('create', '> div', function( e ) {14 e.$currentTarget.css( style_red );15 });16 });17 afterEach(function () {18 $container.remove();19 $container.off('create');20 });21 it('should provide the \'create\' special event.', function() {22 expect( jQuery.event.special.create ).toEqual( jasmine.any(Object) );23 });24 it('should execute the callback if \'on\' function is invoked.', function()25 {26 // when27 $container.append( jQuery('<div>') );28 // then29 expect( $container.find('> div') ).toHaveCss(style_red);30 });31 it('shouldn\'t execute the callback if \'off\' function is invoked.', function()32 {33 // when34 $container.off('create');35 $container.append( jQuery('<div>') );36 // then37 expect( $container.find('> div') ).not.toHaveCss(style_red);38 });39 it('should pass data to the handler in event.data when the event is triggered.', function()40 {41 // given42 $container.on('create', 'div', { name: 'Marco' }, function( e ) {43 console.info('My name is ' + e.data.name);44 });45 // when46 $container.append( jQuery('<div>') );47 // then48 expect( console.info ).toHaveBeenCalledWith( 'My name is Marco' );49 });50 it('shouldn\'t break if the array object has been extended.', function()51 {52 // given53 Array.prototype.newCoolFunction = function() {};54 // then55 expect(function() {56 $container.append( jQuery('<div>') );57 }).not.toThrow();58 });59 it('should execute the callback just one time for each created element.', function()60 {61 // given62 var $element = jQuery('<div>');63 // when64 $container.append( $element );65 // then66 expect( $element ).toHaveCss( style_red );67 // when68 $element.css({ 'color' : 'rgb(0,0,255)' });69 $container.append( jQuery('<div>') );70 // then71 expect( $container.find('> div:eq(0)') ).toHaveCss( style_blue );72 expect( $container.find('> div:eq(1)') ).toHaveCss( style_red );73 });74 it('should execute the callback when elements are created inside other elements.', function()75 {76 // given77 $container.on('create', 'div.inner', function( e ) {78 e.$currentTarget.css( style_green );79 });80 var element = '<span><div class="inner"></div></span>';81 // when82 $container.append( element );83 // then84 expect( $container.find('div.inner') ).toHaveCss( style_green );85 });86 describe('binding the event on jQuery(\'document\')', function()87 {88 afterEach(function () {89 jQuery(document).off('create');90 });91 it('should work.', function()92 {93 // when94 $container.append( jQuery('<a class="pippo">') );95 var counter = 0;96 jQuery(document).on('create', 'a.pippo', function( e ) {97 counter++;98 e.$currentTarget.css( style_red );99 });100 // given101 $container.append( jQuery('<span>') );102 $container.append( jQuery('<span>') );103 $container.append( jQuery('<span>') );104 // when105 $container.append( jQuery('<a class="pippo">') );106 $container.find('> span:eq(0)').replaceWith( jQuery('<a class="pippo">') );107 // then108 expect( counter ).toBe(3);109 expect( $container.find('> a:eq(0)') ).toHaveCss( style_red );110 expect( $container.find('> a:eq(1)') ).toHaveCss( style_red );111 });112 it('should execute the callback when elements are created inside other elements.', function()113 {114 // given115 jQuery(document).on('create', 'div.inner', function( e ) {116 e.$currentTarget.css( style_green );117 });118 var element = '<span><div class="inner"></div></span>';119 // when120 $container.append( element );121 // then122 expect( $container.find('div.inner') ).toHaveCss( style_green );123 });124 });125 describe('should execute the callback when', function()126 {127 var counter;128 beforeEach(function ()129 {130 counter = 0;131 $container.on('create', '> div', function() {132 counter++;133 });134 });135 it('a new element is created before the special event declaration.', function()136 {137 // given138 var _inner_counter = 0;139 // when140 $container.append( jQuery('<div>') );141 $container.on('create', '> div', function() {142 _inner_counter++;143 });144 $container.append( jQuery('<div>') );145 // then146 expect( _inner_counter ).toBe(2);147 expect( counter ).toBe(2);148 expect( $container.find('> div') ).toHaveCss( style_red );149 });150 it('the \'append\' method is invoked.', function()151 {152 // when153 $container.append( jQuery('<div>') );154 $container.append( jQuery('<div>') );155 $container.append( jQuery('<span>') );156 // then157 expect( counter ).toBe(2);158 expect( $container.find('> div') ).toHaveCss( style_red );159 });160 it('the \'prepend\' method is invoked.', function()161 {162 // when163 $container.prepend( jQuery('<div>') );164 $container.prepend( jQuery('<div>') );165 $container.append( jQuery('<span>') );166 // then167 expect( counter ).toBe(2);168 expect( $container.find('> div') ).toHaveCss( style_red );169 });170 it('the \'before\' method is invoked.', function()171 {172 // given173 $container.append( jQuery('<span>') );174 // when175 $container.find('> span').before( jQuery('<div>') );176 $container.find('> span').before( jQuery('<div>') );177 // then178 expect( counter ).toBe(2);179 expect( $container.find('> div') ).toHaveCss( style_red );180 });181 it('the \'after\' method is invoked.', function()182 {183 // given184 $container.append( jQuery('<span>') );185 // when186 $container.find('> span').after( jQuery('<div>') );187 $container.find('> span').after( jQuery('<div>') );188 // then189 expect( counter ).toBe(2);190 expect( $container.find('> div') ).toHaveCss( style_red );191 });192 it('the \'html\' method is invoked.', function()193 {194 // when195 $container.html( '<div></div>' + '<div><div></div></div>' + '<div></div>' + '<span></span>' );196 // then197 expect(counter).toBe(3);198 $container.find('> div').each(function() {199 expect( jQuery(this) ).toHaveCss( style_red );200 });201 });202 it('the \'replaceWith\' method is invoked.', function()203 {204 // given205 $container.append( jQuery('<span>') );206 $container.append( jQuery('<span>') );207 // when208 $container.find('> span:eq(0)').replaceWith( jQuery('<div>') );209 // then210 expect( counter ).toBe(1);211 expect( $container.find('> div') ).toHaveCss( style_red );212 });213 });214 describe('\'event\' param of the callback', function()215 {216 var callback, $element;217 beforeEach(function ()218 {219 // given220 callback = jasmine.createSpy('callback');221 $element = jQuery('<div data-component="hello-world">');222 // TEST-FIX for jQuery < 3.0 - https://jquery.com/upgrade-guide/3.0/#breaking-change-deprecated-context-and-selector-properties-removed223 if ( parseInt(/^[\d]+/.exec( jQuery().jquery )[0], 10) < 3 ) {224 $element.context = $element.get(0);225 $container.context = $container.get(0);226 }227 // when228 $container.on('create', '> div', callback);229 $container.append( $element );230 });231 it('should contain \'type\'.', function()232 {233 // then234 expect( callback ).toHaveBeenCalledWith(jasmine.objectContaining({235 type: 'create'236 }));237 });238 it('should contain \'timeStamp\'.', function()239 {240 // then241 expect( callback ).toHaveBeenCalledWith(jasmine.objectContaining({242 timeStamp: jasmine.any(Number)243 }));244 });245 it('should contain \'currentTarget\'.', function()246 {247 // then248 expect( callback ).toHaveBeenCalledWith(jasmine.objectContaining({249 currentTarget: $element.get(0)250 }));251 });252 it('should contain \'$currentTarget\'.', function()253 {254 // then255 expect( callback ).toHaveBeenCalledWith(jasmine.objectContaining({256 $currentTarget: $element257 }));258 });259 it('should contain \'delegateTarget\'.', function()260 {261 // then262 expect( callback ).toHaveBeenCalledWith(jasmine.objectContaining({263 delegateTarget: $container.get(0)264 }));265 });266 it('should contain \'$delegateTarget\'.', function()267 {268 // then269 expect( callback ).toHaveBeenCalledWith(jasmine.objectContaining({270 $delegateTarget: jQuery( $container.get(0) )271 }));272 });273 it('should contain \'options\'.', function()274 {275 // then276 expect( callback ).toHaveBeenCalledWith(jasmine.objectContaining({277 options: jasmine.any(Function)278 }));279 });280 });...
holiday_spec.js
Source:holiday_spec.js
1describe('Holiday view', function() {2 beforeEach(function() {3 // Stub User roles4 App.currentUserRoles = new App.Collections.CurrentUserRoles([5 {'id':1, 'team_id':1, 'role':'guest'}6 ]);7 this.model = new App.Models.Holiday({8 'description': 'Ruby Day',9 'duration': 1,10 'start': '2015-08-29'11 });12 this.view = new App.Views.Holiday({'model': this.model});13 });14 afterEach(function() {15 this.view.remove();16 });17 describe('as a real object', function() {18 beforeEach(function() {19 setFixtures('<ul class="list-group"></ul>');20 this.container = $('.list-group');21 this.container.append(this.view.render().el);22 });23 afterEach(function() {24 this.view.remove();25 });26 it('has its .model attribute defined', function() {27 expect(this.view.model).toBeDefined();28 });29 it('has its .model of type App.Models.Holiday', function() {30 expect(this.view.model).toEqual(jasmine.any(App.Models.Holiday));31 });32 it('has its .className properly set', function() {33 expect(this.view.el.className).toBe('list-group-item');34 });35 it('has its .tagName properly set', function() {36 expect(this.view.el.tagName.toLowerCase()).toBe('li');37 });38 it('returns the view object with its .render() method', function() {39 expect(this.view.render()).toEqual(this.view);40 });41 });42 describe('for user with manager role', function() {43 beforeEach(function() {44 // Stub User roles45 App.currentUserRoles = new App.Collections.CurrentUserRoles([46 {'id':1, 'team_id':1, 'role':'manager'}47 ]);48 this.view = new App.Views.Holiday({'model': this.model});49 setFixtures('<ul class="list-group"></ul>');50 this.container = $('.list-group');51 this.container.append(this.view.render().el);52 // Inline form input controls53 this.descriptionField = this.container.find('input[name=description]');54 this.fromField = this.container.find('input[name=from]');55 this.toField = this.container.find('input[name=to]');56 // Inline form buttons57 this.updateButton = this.container.find('button[name=update]');58 this.cancelButton = this.container.find('button[name=cancel]');59 });60 describe('responds to jQuery event', function() {61 it('click button[name=delete]', function() {62 this.deleteButton = this.container.find('button[name=delete]');63 spyOn(this.view, 'onDelete');64 this.view.delegateEvents();65 this.deleteButton.trigger('click');66 expect(this.view.onDelete).toHaveBeenCalled();67 });68 it('dblclick .view', function() {69 this.editArea = this.container.find('li .edit');70 this.viewArea = this.container.find('li .view');71 spyOn(this.view, 'enterEditMode').and.callThrough();72 this.view.delegateEvents();73 expect(this.editArea).toHaveCss({'display':'none'});74 this.viewArea.trigger('dblclick');75 expect(this.view.enterEditMode).toHaveBeenCalled();76 expect(this.editArea).toHaveCss({'display':'block'});77 });78 it('click button[name=update]', function() {79 this.updateButton = this.container.find('li button[name=update]');80 spyOn(this.view, 'onUpdate');81 this.view.delegateEvents();82 this.updateButton.trigger('click');83 expect(this.view.onUpdate).toHaveBeenCalled();84 });85 it('click button[name=cancel]', function() {86 this.updateButton = this.container.find('li button[name=cancel]');87 spyOn(this.view, 'onCancel');88 this.view.delegateEvents();89 this.updateButton.trigger('click');90 expect(this.view.onCancel).toHaveBeenCalled();91 });92 });93 describe('exposes HTML control', function() {94 it('button[name=delete]', function() {95 expect(this.container).toContainElement('button[name=delete]');96 });97 it('button[name=update]', function() {98 expect(this.container).toContainElement('button[name=update]');99 });100 it('button[name=cancel]', function() {101 expect(this.container).toContainElement('button[name=cancel]');102 });103 it('input[name=description]', function() {104 expect(this.container).toContainElement('input[name=description]');105 });106 it('input[name=from]', function() {107 expect(this.container).toContainElement('input[name=from]');108 });109 it('input[name=to]', function() {110 expect(this.container).toContainElement('input[name=to]');111 });112 });113 describe('with valid form values', function() {114 beforeEach(function() {115 // Encapsulate model inside of collection to set up url property,116 // as it is in real life117 var collection = new App.Collections.Holidays(this.view.model);118 // Fill in inline form119 this.descriptionField.val('Zero Day');120 this.fromField.val(this.view.attributes.from);121 this.toField.val(this.view.attributes.to);122 this.editArea = this.container.find('.edit');123 this.viewArea = this.container.find('.view');124 this.viewArea.trigger('dblclick');125 });126 it('allows to update record and exits edit mode', function() {127 expect(this.editArea).toHaveCss({'display':'block'});128 expect(this.descriptionField.val()).not.toEqual(this.view.model.get('description'));129 this.updateButton.trigger('click');130 expect(this.descriptionField.val()).toEqual(this.view.model.get('description'));131 expect(this.editArea).toHaveCss({'display':'none'});132 });133 it('allows to exit edit mode without updating record', function() {134 expect(this.editArea).toHaveCss({'display':'block'});135 expect(this.descriptionField.val()).not.toEqual(this.view.model.get('description'));136 this.cancelButton.trigger('click');137 expect(this.descriptionField.val()).not.toEqual(this.view.model.get('description'));138 expect(this.editArea).toHaveCss({'display':'none'});139 });140 });141 describe('with not valid form values', function() {142 beforeEach(function() {143 // Encapsulate model inside of collection to set up url property,144 // as it is in real life145 var collection = new App.Collections.Holidays(this.view.model);146 // Fill in inline form147 this.descriptionField.val('Zero');148 this.fromField.val(this.view.attributes.from);149 this.toField.val(this.view.attributes.to);150 this.editArea = this.container.find('.edit');151 this.viewArea = this.container.find('.view');152 this.viewArea.trigger('dblclick');153 });154 it('does not allow to update record and does not exit edit mode', function() {155 expect(this.editArea).toHaveCss({'display':'block'});156 expect(this.descriptionField.val()).not.toEqual(this.view.model.get('description'));157 this.updateButton.trigger('click');158 expect(this.descriptionField.val()).not.toEqual(this.view.model.get('description'));159 expect(this.editArea).toHaveCss({'display':'block'});160 });161 it('allows to exit edit mode without updating record', function() {162 expect(this.editArea).toHaveCss({'display':'block'});163 expect(this.descriptionField.val()).not.toEqual(this.view.model.get('description'));164 this.cancelButton.trigger('click');165 expect(this.descriptionField.val()).not.toEqual(this.view.model.get('description'));166 expect(this.editArea).toHaveCss({'display':'none'});167 });168 });169 });170 describe('for user without manager role', function() {171 beforeEach(function() {172 setFixtures('<ul class="list-group"></ul>');173 this.container = $('.list-group');174 this.container.append(this.view.render().el);175 });176 it('does not respond to jQuery events', function() {177 expect(this.view.events()).toEqual({});178 });179 describe('does not expose HTML control,', function() {180 it('button[name=delete]', function() {181 expect(this.container).not.toContainElement('button[name=delete]');182 });183 it('button[name=update]', function() {184 expect(this.container).not.toContainElement('button[name=update]');185 });186 it('button[name=cancel]', function() {187 expect(this.container).not.toContainElement('button[name=cancel]');188 });189 it('input[name=description]', function() {190 expect(this.container).not.toContainElement('input[name=description]');191 });192 it('input[name=from]', function() {193 expect(this.container).not.toContainElement('input[name=from]');194 });195 it('input[name=to]', function() {196 expect(this.container).not.toContainElement('input[name=to]');197 });198 });199 });...
rating.spec.js
Source:rating.spec.js
...6 const emoji = page.locator("#star-1"); // Select first emoji7 const stars = page.locator(".stars >> label");8 await stars.nth(0).click(); // Click on the first star9 // Assert selected stars10 await expect(stars.nth(0)).toHaveCSS("color", "rgb(255, 221, 68)");11 // Assert that the related emoji is displayed12 await expect(emoji).toBeChecked();13 // Assert message text for one star14 let msg = await page.$eval(".footer >> .text", (elem) => {15 // Get CSS computed content property16 return window.getComputedStyle(elem, ":before").getPropertyValue("content");17 });18 expect(msg).toMatch("I just hate it");19 // Assert numerically represented rate20 let rate = await page.$eval(".footer >> .numb", (elem) => {21 // Get CSS computed content property22 return window.getComputedStyle(elem, ":before").getPropertyValue("content");23 });24 expect(rate).toMatch("1 out of 5");25 });26 test("Should rate with two stars", async ({ page }) => {27 await page.goto("apps/rating/");28 await expect(page.locator(".stars")).toBeVisible();29 const emoji = page.locator("#star-2"); // Select second emoji30 const emojiPosition = page.locator(".slideImg");31 const stars = page.locator(".stars >> label");32 await stars.nth(1).click(); // Click on the second star33 // Assert selected stars34 await expect(stars.nth(0)).toHaveCSS("color", "rgb(255, 221, 68)");35 await expect(stars.nth(1)).toHaveCSS("color", "rgb(255, 221, 68)");36 // Assert that the related emoji is displayed37 expect(emoji).toBeChecked;38 await expect(emojiPosition).toHaveCSS("margin-top", "-135px");39 // Assert message text for one star40 let msg = await page.$eval(".footer >> .text", (elem) => {41 // Get CSS computed content property42 return window.getComputedStyle(elem, ":before").getPropertyValue("content");43 });44 expect(msg).toMatch("I don't like it");45 // Assert numerically represented rate46 let rate = await page.$eval(".footer >> .numb", (elem) => {47 // Get CSS computed content property48 return window.getComputedStyle(elem, ":before").getPropertyValue("content");49 });50 expect(rate).toMatch("2 out of 5");51 });52 test("Should rate with three stars", async ({ page }) => {53 await page.goto("apps/rating/");54 await expect(page.locator(".stars")).toBeVisible();55 const emoji = page.locator("#star-3"); // Select third emoji56 const emojiPosition = page.locator(".slideImg");57 const stars = page.locator(".stars >> label");58 await stars.nth(2).click(); // Click on the third star59 // Assert selected stars60 await expect(stars.nth(0)).toHaveCSS("color", "rgb(255, 221, 68)");61 await expect(stars.nth(1)).toHaveCSS("color", "rgb(255, 221, 68)");62 await expect(stars.nth(2)).toHaveCSS("color", "rgb(255, 221, 68)");63 // Assert that the related emoji is displayed64 expect(emoji).toBeChecked;65 await expect(emojiPosition).toHaveCSS("margin-top", "-270px");66 // Assert message text for one star67 let msg = await page.$eval(".footer >> .text", (elem) => {68 // Get CSS computed content property69 return window.getComputedStyle(elem, ":before").getPropertyValue("content");70 });71 expect(msg).toMatch("This is awesome");72 // Assert numerically represented rate73 let rate = await page.$eval(".footer >> .numb", (elem) => {74 // Get CSS computed content property75 return window.getComputedStyle(elem, ":before").getPropertyValue("content");76 });77 expect(rate).toMatch("3 out of 5");78 });79 test("Should rate with four stars", async ({ page }) => {80 await page.goto("apps/rating/");81 await expect(page.locator(".stars")).toBeVisible();82 const emoji = page.locator("#star-4"); // Select fourth emoji83 const emojiPosition = page.locator(".slideImg");84 const stars = page.locator(".stars >> label");85 await stars.nth(3).click(); // Click on the fourth star86 // Assert selected stars87 await expect(stars.nth(0)).toHaveCSS("color", "rgb(255, 221, 68)");88 await expect(stars.nth(1)).toHaveCSS("color", "rgb(255, 221, 68)");89 await expect(stars.nth(2)).toHaveCSS("color", "rgb(255, 221, 68)");90 await expect(stars.nth(3)).toHaveCSS("color", "rgb(255, 221, 68)");91 // Assert that the related emoji is displayed92 expect(emoji).toBeChecked;93 await expect(emojiPosition).toHaveCSS("margin-top", "-405px");94 // Assert message text for one star95 let msg = await page.$eval(".footer >> .text", (elem) => {96 // Get CSS computed content property97 return window.getComputedStyle(elem, ":before").getPropertyValue("content");98 });99 expect(msg).toMatch("I just like it");100 // Assert numerically represented rate101 let rate = await page.$eval(".footer >> .numb", (elem) => {102 // Get CSS computed content property103 return window.getComputedStyle(elem, ":before").getPropertyValue("content");104 });105 expect(rate).toMatch("4 out of 5");106 });107 test("Should rate with five stars", async ({ page }) => {108 await page.goto("apps/rating/");109 await expect(page.locator(".stars")).toBeVisible();110 const emoji = page.locator("#star-5"); // Select fifth emoji111 const emojiPosition = page.locator(".slideImg");112 const stars = page.locator(".stars >> label");113 await stars.nth(4).click(); // Click on the fifth star114 // Assert selected stars115 await expect(stars.nth(0)).toHaveCSS("color", "rgb(255, 221, 68)");116 await expect(stars.nth(1)).toHaveCSS("color", "rgb(255, 221, 68)");117 await expect(stars.nth(2)).toHaveCSS("color", "rgb(255, 221, 68)");118 await expect(stars.nth(3)).toHaveCSS("color", "rgb(255, 221, 68)");119 await expect(stars.nth(4)).toHaveCSS("color", "rgb(255, 221, 68)");120 // Assert that the related emoji is displayed121 expect(emoji).toBeChecked;122 await expect(emojiPosition).toHaveCSS("margin-top", "-540px");123 // Assert message text for one star124 let msg = await page.$eval(".footer >> .text", (elem) => {125 // Get CSS computed content property126 return window.getComputedStyle(elem, ":before").getPropertyValue("content");127 });128 expect(msg).toMatch("I just love it");129 // Assert numerically represented rate130 let rate = await page.$eval(".footer >> .numb", (elem) => {131 // Get CSS computed content property132 return window.getComputedStyle(elem, ":before").getPropertyValue("content");133 });134 expect(rate).toMatch("5 out of 5");135 });136});
Stylus.browser.js
Source:Stylus.browser.js
1/* global $ */2describe('alchemy.lib.Stylus', function () {3 'use strict';4 var Stylus = require('./../../lib/Stylus');5 beforeEach(function () {6 setFixtures([7 '<div id="foo">FOO',8 '<div id="bar" class="bar">BAR',9 '<div id="baz" class="baz">BAZ</div>',10 '</div>',11 '</div>',12 ].join());13 this.testSubject = Stylus.brew();14 });15 afterEach(function () {16 this.testSubject.dispose();17 this.testSubject = null;18 });19 describe('dispose', function () {20 it('clears the stored data', function () {21 // prepare22 // execute23 this.testSubject.dispose();24 // verify25 expect(this.testSubject.sheet).toBeFalsy();26 expect(this.testSubject.rules).toBeFalsy();27 });28 it('removes css rules when beeing disposed', function () {29 // prepare30 this.testSubject.setRules({31 '#foo': {'color': '#FF0000'},32 '#bar': {'color': '#00FF00'},33 '#baz': {'color': '#0000FF'},34 });35 expect($('div#foo')).toHaveCss({color: 'rgb(255, 0, 0)'});36 expect($('div#bar')).toHaveCss({color: 'rgb(0, 255, 0)'});37 expect($('div#baz')).toHaveCss({color: 'rgb(0, 0, 255)'});38 // execute39 this.testSubject.dispose();40 // verify41 expect($('div#foo')).not.toHaveCss({color: 'rgb(255, 0, 0)'});42 expect($('div#bar')).not.toHaveCss({color: 'rgb(0, 255, 0)'});43 expect($('div#baz')).not.toHaveCss({color: 'rgb(0, 0, 255)'});44 });45 });46 describe('setRules', function () {47 it('allows to render css', function () {48 // prepare49 // execute50 this.testSubject.setRules({51 '#foo': {'color': '#FF0000'},52 '#bar': {'color': '#00FF00'},53 '#baz': {'color': '#0000FF'},54 });55 // verify56 expect($('div#foo')).toHaveCss({color: 'rgb(255, 0, 0)'});57 expect($('div#bar')).toHaveCss({color: 'rgb(0, 255, 0)'});58 expect($('div#baz')).toHaveCss({color: 'rgb(0, 0, 255)'});59 });60 it('allows to override css rules', function () {61 // prepare62 this.testSubject.setRules({ '#foo': { 'color': '#00FF00', }, });63 // execute64 this.testSubject.setRules({ '#foo': {'color': '#FF00FF'}, });65 // verify66 expect($('div#foo')).toHaveCss({ 'color': 'rgb(255, 0, 255)', });67 });68 it('supports nested css rules', function () {69 // prepare70 // execute71 this.testSubject.setRules({72 '#foo': {73 'color': '#FF0000',74 '#bar': {75 'color': '#00FF00',76 '#baz': {77 'color': '#0000FF',78 },79 },80 },81 });82 // verify83 expect($('div#foo')).toHaveCss({color: 'rgb(255, 0, 0)'});84 expect($('div#bar')).toHaveCss({color: 'rgb(0, 255, 0)'});85 expect($('div#baz')).toHaveCss({color: 'rgb(0, 0, 255)'});86 });87 it('supports "&" in nested rules', function () {88 // prepare89 // execute90 this.testSubject.setRules({91 'div': {92 'color': '#FF0000',93 '&#bar': {94 'color': '#00FF00',95 },96 },97 });98 // verify99 expect($('div#foo')).toHaveCss({color: 'rgb(255, 0, 0)'});100 expect($('div#bar')).toHaveCss({color: 'rgb(0, 255, 0)'});101 expect($('div#baz')).toHaveCss({color: 'rgb(255, 0, 0)'});102 });103 it('supports "," in nested rules', function () {104 // prepare105 // execute106 this.testSubject.setRules({107 '#foo': {108 'color': '#FF0000',109 '#bar, #baz': {110 'color': '#00FF00',111 },112 },113 });114 // verify115 expect($('div#foo')).toHaveCss({color: 'rgb(255, 0, 0)'});116 expect($('div#bar')).toHaveCss({color: 'rgb(0, 255, 0)'});117 expect($('div#baz')).toHaveCss({color: 'rgb(0, 255, 0)'});118 });119 });...
accordion-invalidValues.spec.js
Source:accordion-invalidValues.spec.js
1describe('ACCORDION - DEFAULT - DOM element passed', function() {2 beforeEach(function() {3 jasmine.getFixtures().fixturesPath = fixturePath;4 loadFixtures(accordionFixture);5 var accordion = document.getElementById('accordion');6 this.accordion = new Accordion({7 element: accordion8 });9 });10 sharedTests();11});12describe('ACCORDION - DEFAULT - ID passed', function() {13 beforeEach(function() {14 jasmine.getFixtures().fixturesPath = fixturePath;15 loadFixtures(accordionFixture);16 this.accordion = new Accordion({17 element: 'accordion'18 });19 });20 sharedTests();21});22function sharedTests() {23 describe('behavior', function() {24 it('should have no open tab when openTab value is out of range', function() {25 expect( $('#accordion > div')[0] ).toHaveCss({ height: '0px' });26 expect( $('#accordion > div')[1] ).toHaveCss({ height: '0px' });27 expect( $('#accordion > div')[2] ).toHaveCss({ height: '0px' });28 });29 it('.open(99) should do nothing', function() {30 expect( $('#accordion > div')[0] ).toHaveCss({ height: '0px' });31 expect( $('#accordion > div')[1] ).toHaveCss({ height: '0px' });32 expect( $('#accordion > div')[2] ).toHaveCss({ height: '0px' });33 this.accordion.open(99);34 expect( $('#accordion > div')[0] ).toHaveCss({ height: '0px' });35 expect( $('#accordion > div')[1] ).toHaveCss({ height: '0px' });36 expect( $('#accordion > div')[2] ).toHaveCss({ height: '0px' });37 });38 it('.close(-99) should do nothing', function() {39 this.accordion.open(1);40 expect( $('#accordion > div')[0] ).toBeVisible();41 this.accordion.open(2);42 expect( $('#accordion > div')[0] ).toBeVisible();43 this.accordion.open(3);44 expect( $('#accordion > div')[0] ).toBeVisible();45 this.accordion.close(-99);46 expect( $('#accordion > div')[0] ).toBeVisible();47 expect( $('#accordion > div')[1] ).toBeVisible();48 expect( $('#accordion > div')[2] ).toBeVisible();49 });50 it('should do nothing when clicked not on title', function() {51 var button = $('#accordion .js-Accordion-title')[0],52 content = $('#accordion .js-Accordion-content')[0];53 // first scenario:54 // click on title opens and hides content55 expect(content).toHaveCss({ height: '0px' });56 var spyEvent = spyOnEvent(button, 'click');57 button.click();58 expect('click').toHaveBeenTriggeredOn(button);59 expect(spyEvent).toHaveBeenTriggered();60 expect(content).toBeVisible();61 button.click();62 expect(content).toHaveCss({ height: '0px' });63 // second scenario:64 // click happens not on title, but content container65 var spyEvent = spyOnEvent(content, 'click');66 content.click();67 expect('click').toHaveBeenTriggeredOn(content);68 expect(spyEvent).toHaveBeenTriggered();69 expect(content).toHaveCss({ height: '0px' });70 // still works on title click71 button.click();72 expect(content).toBeVisible();73 });74 });...
Using AI Code Generation
1const { test, expect } = require("@playwright/test");2test("test", async ({ page }) => {3 await expect(page.locator(".navbar__inner")).toHaveCSS({4 "background-color": "rgb(255, 255, 255)",5 });6});7The above code is working fine. But I want to use the same method in my test file. I have imported the above test.js file in my test file using require() method. But I am getting the following error:8Error: expect(...).toHaveCSS is not a function9 at Object.<anonymous> (/Users/sayali/Desktop/Playwright/sample.js:5:10)10await expect(page.locator(".navbar__inner")).toHaveCSS({11 "background-color": "rgb(255, 255, 255)",12 });13await expect(page.locator(".navbar__inner")).toHaveCSS({14 "background-color": "rgb(255, 255, 255)",15 });16await expect(page.locator(".navbar__inner")).toHaveCSS({17 "background-color": "rgb(255, 255, 255)",18 });
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('should have css', async ({ page }) => {3 await expect(page.locator('.navbar__inner')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');4});5const { test, expect } = require('@playwright/test');6test('should have css', async ({ page }) => {7 await expect(page.locator('.navbar__inner')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');8});9const { test, expect } = require('@playwright/test');10test('should have css', async ({ page }) => {11 await expect(page.locator('.navbar__inner')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');12});13const { test, expect } = require('@playwright/test');14test('should have css', async ({ page }) => {15 await expect(page.locator('.navbar__inner')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');16});17const { test, expect } = require('@playwright/test');18test('should have css', async ({ page }) => {19 await expect(page.locator('.navbar__inner')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');20});21const { test, expect } = require('@playwright/test');22test('should have css', async ({ page }) => {23 await expect(page.locator('.navbar__inner')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');24});25const { test, expect
Using AI Code Generation
1const { test, expect } = require("@playwright/test");2test("test", async ({ page }) => {3 const element = await page.$("input[name='q']");4 await expect(element).toHaveCSS({5 "border-color": "rgb(102, 102, 102)",6 });7});8const { test, expect } = require("@playwright/test");9test("test", async ({ page }) => {10 const element = await page.$("input[name='q']");11 await expect(element).toHaveCSS({12 "border-color": "rgb(102, 102, 102)",13 });14});
Using AI Code Generation
1expect(page.locator('div')).toHaveCSS('background-color', 'rgb(255, 255, 255)');2expect(page.locator('div')).toHaveCSS('background-color', 'white');3expect(page.locator('div')).toHaveCSS('background-color', '#ffffff');4expect(page.locator('div')).toHaveCSS('background-color', 'rgb(255, 255, 255)');5expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');6expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');7expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');8expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');9expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');10expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');11expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');12expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255, 1)');13expect(page.locator('div')).toHaveCSS('background-color', 'rgba(255, 255, 255
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!