Skip to content

Instantly share code, notes, and snippets.

@dotherightthing
Last active November 12, 2020 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dotherightthing/e0e4086cee034389eb172d9fc088c5df to your computer and use it in GitHub Desktop.
Save dotherightthing/e0e4086cee034389eb172d9fc088c5df to your computer and use it in GitHub Desktop.
Cypress keycode test
describe('Keydown test', function () {
before(function () {
cy.get('body').then(function ($body) {
var stub = '';
stub += '<span id="focusable-div" class="listener" tabindex="0" style="border: 1px solid;">Element 1</span>';
stub += '<button type="button" id="focusable-button" class="listener">Element 2</button>';
stub += '<span id="target" tabindex="0" style="border: 1px solid;">Target</span>';
// note: can't use jQuery here
stub += "<script>";
stub += "document.querySelectorAll('.listener').forEach(($el) => { $el.addEventListener('keydown', (event) => {";
stub += "$el.setAttribute('data-pressed', event.key);";
stub += "document.querySelector('#target').focus();";
stub += "}); });";
stub += "</script>";
$body.html(stub);
});
});
context('tests', () => {
beforeEach(() => {
cy.get('#target').as('focusTarget');
});
['#focusable-div', '#focusable-button'].forEach((selector) => {
it(selector, () => {
cy.get(selector)
.focus()
.should('have.focus')
.type('{rightarrow}')
.should('have.attr', 'data-pressed', 'ArrowRight');
cy.get('@focusTarget')
.should('have.focus');
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment