Search code examples
addeventlistenertestcafe

Can Testcafe fire the event listener of an <input type=number> in my project?


My project code:

html:
<input id="min-days" type="number" onchange="javascript=onRefresh();" oninput="validity.valid||(value='');" placeholder="0 days" min="0" max="99999" />

JavaScript:
var durationInput = document.getElementById("min-days");
durationInput.addEventListener("keydown", function (event) {
    if (event.code == "ArrowUp") {
        durationInput.value = parseInt(durationInput.value || 0) + 364;
    } …
});

I'd like my Testcafe test function to enter an ArrowUp to the input that the event listener catches.

While the project works, I've been unable to get Testcafe to trigger the event handler. I started with pressKey('up') and the following. None has worked.

#1
test('Date up arrow increments by 365 from 0 on up arrow', 
    async t => {

        await t.eval(() => {
            const input = document.querySelector('#min-days');
            const event = new KeyboardEvent('keydown', { key: 'ArrowUp' });
            input.dispatchEvent(event);
        });

        await t.expect(Selector('#min-days').value).eql('365');
    });

#2
test('Date up arrow increments by 365 from 0 on up arrow',
    async t => {
        const minDays = Selector('#min-days');
        const getInputNode = ClientFunction(() =>
            document.querySelector('#min-days'));

        await t.eval(() => {
            const input = document.querySelector('#min-days');
            const event = new KeyboardEvent('keyup', { key: 'ArrowUp' });
            input.dispatchEvent(event);
        });
        await t.expect(minDays.value).eql('365');
    });

Running testcafe asserts:

 1) AssertionError: expected '' to deeply equal '365'
      
      + expected - actual
      
      -''
      +365

Solution

  • The event.code property is difficult to implement. Please read the information outlined here: https://github.com/DevExpress/testcafe/issues/3146#issuecomment-444070308

    As a workaround, you can use the following approach:

    await t.dispatchEvent('#min-days', 'keydown', { code: 'ArrowUp' })