Writing a test for CodeMirror - codemirror

I would like to write a simple test for CodeMirror
test(' codemirror ', () => {
let text = document.createElement("div");
let settings = {}
codemirror(text, { ...settings, value: '' });
});
However when I run this I get :
TypeError: document.body.createTextRange is not a function
at range (A:\frontend\node_modules\codemirror\lib\codemirror.js:94:25)
at hasBadBidiRects (A:\frontend\node_modules\codemirror\lib\codemirror.js:1343:12)
at buildLineContent (A:\frontend\node_modules\codemirror\lib\codemirror.js:1838:9)
at updateExternalMeasurement (A:\frontend\node_modules\codemirror\lib\codemirror.js:2442:28)
at prepareMeasureForLine (A:\frontend\node_modules\codemirror\lib\codemirror.js:2478:14)
at measureChar (A:\frontend\node_modules\codemirror\lib\codemirror.js:2451:34)
at endOperation_R2 (A:\frontend\node_modules\codemirror\lib\codemirror.js:3766:24)
at endOperations (A:\frontend\node_modules\codemirror\lib\codemirror.js:3732:7)
at A:\frontend\node_modules\codemirror\lib\codemirror.js:3719:5
at finishOperation (A:\frontend\node_modules\codemirror\lib\codemirror.js:2132:5)
at endOperation (A:\frontend\node_modules\codemirror\lib\codemirror.js:3716:3)
at new CodeMirror$1 (A:\frontend\node_modules\codemirror\lib\codemirror.js:7448:3)
at CodeMirror$1 (A:\frontend\node_modules\codemirror\lib\codemirror.js:7389:49)
What am I doing wrong here?
My import looks like this :
import codemirror from 'codemirror';
And I am using : "codemirror": "5.25.0",

I managed to stub out some functions and now it works. It is not a very nice solution though :(
test(' codemirror test ', () => {
let div = document.createElement("div");
document.body.createTextRange = (elem) => {
let textRange = {
getBoundingClientRect: ()=>1,
getClientRects: ()=>1
}
return textRange;
}
codemirror(div);
});

Related

Tell babel to transpile down to NodeJS

I use typescript and I'm building a lambda layer but lambda layer seem to be strict with module.exports.myHelperFunction rather than exports.myHelperFunction, the later doesn't work when you try to import it, it will fail.
So What I want is if I have the following code:
export function myHelperUtility () {
let a = {};
return { ...a };
}
it should transpile to:
"use strict";
function myHelperUtility () {
let a = {};
return { ...a };
}
module.exports.myHelperUtility = myHelperUtility;
Rather than:
"use strict";
exports.__esModule = true;
exports.test = test;
function test() {
let a = {};
return { ...a };
}
Found a way to make it work, instead of using #babel/preset-env, I completely removed it and used #babel/plugin-transform-modules-commonjs with the following options:
{
strict: true,
loose: true,
importInterop: 'node'
}
which did not produce what I wanted to achieve BUT since it removes the __esmodule and _interoprequiredefault, it will work!

how to put verification in pageobject model in protractor

I have a code (credit to #kishanpatel) Traverse-through-each-row-for-a-column-text which will verify whether the value is added in grid or not. i want to put this in my page object. i was thinking to add the elements into page object and the if condition in a different helper file similar to selenium but i am not sure is that the right appraoch. see the details below.
if I call the mo.helper in spec.ts, it says gridcheck.ispresent() is not a function. How to handle this scenario?
code:
it('verify the grid that master obligation is added', function () {
var testvar = "'test_protractor'";
var row_check = element(by.xpath("//div[contains(text()," + testvar + ")]"));
if (row_check.isPresent()) {
row_check.getText().then(function (msg) {
if (row_check.isPresent()) {
console.log("Grid contains========== " + msg);
}
});
}
});
i have the below method in mo.ts(page object page):
this.grid = function (value) {
// var testvar = "'test_protractor'";
var row_check = element(by.xpath("//div[contains(text()," + value + ")]"));
return require('./mohelper.ts')
}
}
mohelper.ts:
require('../page/mo.ts')
var mohelper = function () {
this.gridvaluepresent = function () {
require('../page/mo.ts')
var gridcheck = mo.grid();
if(gridcheck.isPresent()) {
gridcheck.getText().then(function (msg) {
if (gridcheck.isPresent()) {
console.log("Grid contains========== " + msg);
}
})
}
}
}
module.exports = new mohelper();
spec.ts:
it('go to corresponding module and verify whether the master obligation is added ', function () {
browser.sleep(10000);
taxhome.selectmodule;
taxhome.selectmoduledropdown(1);
mo.grid("test_protractor");
mohelper.gridvaluepresent();
});
Couple of things here to be considered -
1) Most of the protractor's api methods are asynchronous i.e. they return promises you have to resolve/reject them to perform actions.
isPresent() also returns a promise, you need to resolve it-
var row_check = element(by.xpath("//div[contains(text()," + value + ")]"));
row_check.isPresent().then(function(present) {
if(present) { // it returns a boolean value
row_check.getText().then(function (msg) {
console.log("Grid contains========== " + msg);
});
}
});
2) Since you are using TypeScript , use its syntax rather than conventional js-
let row_check = element(by.xpath("//div[contains(text()," + value + ")]")); // Block scoped variable using 'let'
row_check.isPresent().then((present) => { // notice the thick arrow
if(present) {
row_check.getText().then((msg) => {
console.log("Grid contains========== " + msg);
});
}
});
3) Maintain Page Objects efficiently and readable-
All the helper methods, elements etc. for a single page should go in a single page object. Write them in separate classes, typescript uses the concept of classes and transpiles them to global functions.
moHelper.ts
import {ElementFinder, element} from 'protractor';
export class MoHelper {
public row_check: ElementFinder; // its of element finder type
gridValueCheck(value : string) {
row_check = element(by.xpath("//div[contains(text()," + value + ")]")); // please use Css selectors instead of Xpath!
row_check.isPresent().then((present) => {
if(present) {
row_check.getText().then((msg) => {
return msg; // here you are returning the msg of the row from your page!
});
}
});
}
}
Your spec.ts should validate that row msg!
import {MoHelper} from './moHelper.ts'
let mo: MoHelper = new MoHelper();
it('go to corresponding module and verify whether the master obligation is added ', () => {
browser.sleep(10000); // please refrain from using sleeps instead use Expected Conditions
taxhome.selectmodule;
taxhome.selectmoduledropdown(1);
expect(mo.gridValueCheck("test_protractor")).toEqual("Your Expected Message");
});
Please find the links for your reference to understand the above in more detail-
isPresent
Getting started with typescript
Using page objects in protractor/style guide
Expected Conditions

CoffeeScript code-complete for Web IDE

Is there a web based code-complete API/IDE for coffee script?
Ace Editor and CodeMirror have good syntax highlighting and lint-based syntax support, and what I would like to add to my app (Node-WebKit-REPL) is code-complete support
Unfortunately neither CodeMirror nor Ace have autocompleters specially for coffeescript, but they both have an api to add a completer.
here's a simple example to show how do it for ace
var lang = require("ace/lib/lang")
var languageTools = require("ace/ext/language_tools")
editor = ace.edit("editor")
editor.setOptions({
enableBasicAutocompletion: true,
enableLiveAutocompletion: true, // this does not work very well atm
mode: "ace/mode/coffee"
})
var evalCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
var completions = [];
var props = Object.keys(window);
props.forEach(function(key){
completions.push({
value: key,
meta: 'window',
type: 'eval',
score: 1000
});
})
callback(null, completions)
},
getDocTooltip: function(item) {
if (item.type == 'eval' && !item.docHTML) {
var o = window[item.value]
var type = typeof o
item.docHTML = "<b>" + type + "</b><br>"
+ lang.escapeHTML(o + "");
}
}
}
editor.completers = [evalCompleter, languageTools.keyWordCompleter,
languageTools.snippetCompleter, languageTools.textCompleter
];
of course in a real application you will need some kind of parser to get the expression before the . to evaluate
http://sevin7676.github.io/Ace.Tern/demo.html also can be useful.

Is there a way to resolve multiple promises with Protractor?

I have this:
element(by.id('x')).sendKeys('xxx').then(function(text) {
element(by.id('y')).sendKeys('yyy').then(function(text) {
element(by.id('z')).sendKeys('zzz').then(function(text) {
expect(element(by.id('myButton')).isEnabled()).toBe(true);
})
});
});
The button 'myButton' is enabled when the elements 'x', 'y' and 'z' all have values. It's my understanding that sendKeys returns a promise.
So is this the only way that I can check if 'myButton' which depends on data in all the three fields is enabled?
You don't need to chain any promises because protractor will wait until all the statements are done: https://github.com/angular/protractor/blob/master/docs/control-flow.md
element(by.id('x')).sendKeys('xxx');
element(by.id('y')).sendKeys('yyy');
element(by.id('z')).sendKeys('zzz');
expect(element(by.id('myButton'));
If you want to resolve multiple promises use:
var webdriver = require('selenium-webdriver');
webdriver.promise.fullyResolved(promises);
For example: https://github.com/angular/protractor/blob/d15d35a82a5a2/lib/protractor.js#L327
this is a bit after the fact, but:
var x = element(by.id('x')).sendKeys('xxx');
var y = element(by.id('y')).sendKeys('yyy');
var z = element(by.id('z')).sendKeys('zzz');
myFun(x,y,z).then(function(){
expect(element(by.id('myButton')).isEnabled()).toBe(true);
});
// in a common function library
function myFun(Xel,Yel,Zel) {
return protractor.promise.all([Xel,Yel,Zel]).then(function(results){
var xText = results[0];
var yText = results[1];
var zText = results[2];
});
}
but an even better way:
var x = element(by.id('x')).sendKeys('xxx');
var y = element(by.id('y')).sendKeys('yyy');
var z = element(by.id('z')).sendKeys('zzz');
myFun(x,y,z);
//isEnabled() is contained in the expect() function, so it'll wait for
// myFun() promise to be fulfilled
expect(element(by.id('myButton')).isEnabled()).toBe(true);
// in a common function library
function myFun(Xel,Yel,Zel) {
return protractor.promise.all([Xel,Yel,Zel]).then(function(results){
var xText = results[0];
var yText = results[1];
var zText = results[2];
});
}
another way is to chain the .thens together:
element(by.id('x')).sendKeys('xxx').
then(function(xtext){
element(by.id('y')).sendKeys('yyy');
}).then(function(ytext){
element(by.id('z')).sendKeys('zzz');
}).then(function(ztext){
expect(element(by.id('myButton')).isEnabled()).toBe(true);
});
it seems protractor supports all - protractor.promise.all
read more at:
https://github.com/angular/protractor/issues/2062#issuecomment-94030055
describe('promise.all', function() {
it('should greet the named user', function() {
browser.get('http://juliemr.github.io/protractor-demo');
$('div').click().then(function () {
return protractor.promise.all([
$('h3').getText(),
$('h4').getText()
]);
}).then(function (params) {
console.log('A');
});
});
it('does something else', function() {
console.log('B');
});
If you want to return an object instead of a list, seems you can also do that - used it and it's awesome
element.all(by.css('.fc-event-inner')).map(function(el) {
return {
time: el.findElement(by.className('fc-event-time')).getText(),
title: el.findElement(by.className('fc-event-title')).getText()
}
});
See the properties are actually promises.. protractor will resolve them.

How to globally add a custom locator to Protractor?

I wrote a custom locator for Protractor that finds anchor elements by their ui-sref value. In my specs I just used by.addLocator to add the custom locator, but I figured this might be a cool thing to publish and have other people use it.
The goal is to add this custom locator to the global Protractor object so it can be used in any of your specs.
My initial approach was to add this functionality in the onPrepare block of the Protractor config. Something like the pseudocode below:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
That require statement would just execute this function:
function (ptorInstance) {
ptorInstance.by.addLocator('uiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};
The problem is that by is not defined on the protractor object available in the onPrepare block. This means that I cannot use the .addLocator method.
Try the following:
function () {
by.addLocator('uiSref', function (toState, opt_parentElement) {
...
By should be in the global scope.
The protractor object passed to the onPrepare block has a By property. That By property has an inherited enumerable property named addLocator. My understanding of JavaScript is pretty shallow so it really threw me off that when I console.log'ed the protractor.By it returned {}, but if I did for (var propName in protractor.By) it would show me all the "hidden" properties. I'm still struggling to understand that bit.
Working code:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
The require would execute the function below:
function (ptor) {
ptor.By.addLocator('linkUiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};