Search code examples
javascriptseleniumautomated-testscodemirrornightwatch.js

Using nightwatchjs to test a page with a CodeMirror component in it


I am attempting to edit a query on a page in a web application that uses a CodeMirror component. I am using nightwatchjs with selenium in chrome for the test. I can't set the underlying textarea element as it is not visible. Nightwatchjs setValue method doesn't work as the query is in an editable div.

Example Attempt:

module.exports = {

'Testing save code change' : function (browser) {

browser
  .url("http://codemirror.net/index.html")
  .waitForElementVisible("#demo", 3000)
  .waitForElementVisible('.CodeMirror-code div:nth-child(3) .cm-string', 3000)
  .setValue('.CodeMirror-code div:nth-child(3) .cm-string', 'New String');

 }

};

Can anyone suggest an approach that will work?


Solution

  • You could click the CodeMirror element and then use keys() to do the typing.

    browser.click('.CodeMirror textarea').keys('New String');
    

    This will prepend the value to whatever is already inside the text area, so you'd have to do a bit more wrangling to delete whatever's there if you need to.

    Alternatively, you could use nightwatch.js's execute() function to call CodeMirror's setValue() directly, relying on the fact that you can get the CodeMirror instance directly from the DOM element.

    browser.execute(function(text) {
        document.getElementsByClassName('CodeMirror')[0].CodeMirror.setValue(text);
    }, ["you could also pass a variable in here"]);
    

    Unlike the first option, it won't trigger all the same things as typing directly would (e.g. hints/autocompletions) but it'll correctly set an exact value.