mercredi 13 décembre 2017

How do I test cursor/caret position in vue component with karma mocha setup?

I'm trying to test the follwing method one of my components implements:

fillTextarea(text, field) {
    let startPos = field.selectionStart;
    let before = field.value.substr(0, startPos);
    let after = field.value.substr(field.selectionEnd, (field.value.length - field.selectionEnd));
    field.value = before + text + after;
    this.content = field.value;
}

The method inserts a given text into a textfield at the cursor/caret position. Now my question. I am currently struggeling to find a way of testing the insertion at the caret position. The insertion-test itself works fine, but i right now i can only test insertion at position 0.

My test setup is vue with mocha, karma and phantomjs. Usual unit test setup is done before (cm is the component). content in $data is initialized with 'test'. This is my attempt:

it('should add the given Text to the content area at the cursor position', (done) => {
    Vue.config.errorHandler = done;
    Vue.nextTick(() => {
      cm.$el.querySelector('#content').focus();
      cm.$el.querySelector('#content').setSelectionRange(4, 4);
      cm.fillTextarea(' example', cm.$el.querySelector('#content'));
      expect(cm.$el.querySelector('#content').value).to.equal('test example');
      done();
    });
  });

But it seems like .focus() and .setSelectionRange() are simply not executed. console.logs confirmed that selectionStart is 0 right after the call to setSelectionRange(). I tried all versions for different Browsers i found on google and stackoverflow, even jquery but it always inserts it at position 0.

Any other ideas what i could try or what i have missed?

Aucun commentaire:

Enregistrer un commentaire