Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pgengler/a440ba3bf92d618cdf4c6866bd28aadb to your computer and use it in GitHub Desktop.
Save pgengler/a440ba3bf92d618cdf4c6866bd28aadb to your computer and use it in GitHub Desktop.
Testing drag-and-drop - Ember NYC 2016-04-28
import Ember from 'ember';
export default Ember.Component.extend({
draggable: true,
attributeBindings: [ 'draggable' ],
dragStart(event) {
event.dataTransfer.setData('text/data', this.get('id'));
}
});
import Ember from 'ember';
export default Ember.Component.extend({
dragOver(event) {
// We need to preventDefault() to be able to receive a drop event.
// See https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations#droptargets
event.preventDefault();
},
drop(event) {
let droppedId = event.dataTransfer.getData('text/data');
if (this.get('acceptId') === droppedId) {
// matched
} else {
// didn't match
}
}
});
import Ember from 'ember';
export class DataTransferMock {
constructor() {
this.savedData = { };
}
setData(format, data) {
this.savedData[ format ] = data;
}
getData(format) {
return this.savedData[ format ];
}
}
export default Ember.Test.registerAsyncHelper('dragAndDrop',
function(app, draggedElementSelector, targetElementSelector) {
let draggedElement = find(draggedElementSelector);
let dropTargetElement = find(targetElementSelector);
Ember.run(function() {
let dragStartEvent = Ember.$.Event('dragstart');
dragStartEvent.dataTransfer = new DataTransferMock();
draggedElement.trigger(dragStartEvent);
let dropEvent = Ember.$.Event('drop');
dropEvent.dataTransfer = dragStartEvent.dataTransfer;
dropTargetElement.trigger(dropEvent);
draggedElement.trigger('dragend');
});
});
test('the score updates when dragging/dropping cards', function(assert) {
startGame();
dragAndDrop('.card:eq(0)', '.valid-target');
andThen(() => {
assert.containsExactly('.points', '10', 'score should be 10 points after a successful match');
});
dragAndDrop('.card:eq(0)', '.invalid-target');
andThen(() => {
assert.containsExactly('.points', '5', 'score should be decreased to 5 after a miss');
});
});
Testing drag-and-drop
Phil Gengler
@pgengler
Ember NYC
April 28, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment