ReactJS Simulate change value / unit testing - unit-testing

i try to simulate a test of a value change on my InputText component. I really don't know how to make that. I just know I must use the ref and the onChange method. But when I put a ref on my test I got an error like "you might be adding a ref to a component that was not created inside a component's render method".
Edit = I give a ref in the render of my InputText component
This is the render of my InputText component
render: function () {
console.log('passerender');
var attrs = this.generateAttributes();
var type = this.props.area ? "textarea" : "text";
return (
<Input
className={this.props.menuClassName}
type={type}
{...attrs}
{...this.props.evts}
className={this.props.menuClassName}
onChange = {this.handleChange}
onBlur = {this.handleBlur}
value={this.state.value}
ref = "InputField"
hasFeedback
/>
);
}
});
This is my test page of my InputText component:
var React = require('react'),
InputText = require('../resources/assets/js/testcomponents/InputText.js').InputTextEditable,
TestUtils = require('react-addons-test-utils'),
ReactDOM = require('react-dom');
describe('InputText', function () {
var InputElement = TestUtils.renderIntoDocument(
<InputText
area={false}
//evts={{onChange: handleChange}}
attributes={{
label:'Test Input Isole',
name:'InputTextArea',
value: '',
wrapperClassName: 'col-md-4',
labelClassName: 'col-md-2',
groupClassName: 'row'
}}
//ref="InputField"
editable={true}/>);
var DomElement = ReactDOM.findDOMNode(InputElement);
var inputV = ReactDOM.findDOMNode(InputElement.refs.InputField);
var input = DomElement.getElementsByTagName('input')[0];
var inputspan = DomElement.getElementsByTagName('span')[1];
it('updates input value on key press', function () {
inputV.value = 'test';
expect(input.getAttribute('value')).toEqual('');
TestUtils.Simulate.change(inputV);
TestUtils.Simulate.keyDown(inputV, {key: "Entrer", keyCode: 13, which: 13});
expect(input.getAttribute('value')).toEqual('test');
});

You can use findRenderedComponentWithType or findRenderedDOMComponentWithTag
You don't need to call findDOMNode explicitly, because TestUtils has done this for you.
var InputElement = TestUtils.renderIntoDocument(
<InputText {...yourProps}/>
);
// Assuming there is only one <input /> DOM element in your Input
var input = TestUtils.findRenderedComponentWithType(InputElement, Input)
// or you can just find <input /> directly
var input = TestUtils.findRenderedDOMComponentWithTag(InputElement, 'input');
TestUtils.Simulate.change(input);
TestUtils.Simulate.keyDown(input, {key: "Entrer", keyCode: 13, which: 13});

Ok I find the problem of the syntax error. It was on my html5validator on my input mixin. I put a try/catch to solve this :
var html5Validity = true;
if (DOM !== undefined) {
try {
html5Validity = $(DOM).find(':invalid').length == 0;
console.log('passe');
} catch (e) {
console.log('html5Validity = [catch]');
html5Validity = true;
}
}
attrs = _.extend({'data-valid': validation.isValid && html5Validity}, attrs);
Now it's OK ! Thank you ! :)

Related

How to save multiple bool from list in Flutter with SharedPreferences

I have created a bool List:
List<bool> switchbool = [true, true, true, true];
On change of a switch, the value change (pretty obvious...). But I would like to store those information exactly as they are in the list, because I use them like this:
Switch(
value: switchbool[index],
onChanged: (value) {
_saveBoolFromSharedPref(value, app[index]);
setState(() {
switchbool[index] = value;
});
},
)
But with this it doesn't load the true or false stored in the sharedPreferences that I saved:
Future<void> _getBoolFromSharedPref() async {
final prefs = await SharedPreferences.getInstance();
switchbool.length = app.length;
for (var i = 0; i < app.length; i += 1) {
final myBool = prefs.getBool(app[i]) ?? false;
}
}
And here is the _saveBoolFromSharedPref:
Future<bool> _saveBoolFromSharedPref(bool value, String appName) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(appName, value);
//print(switchbool);
}
Any advice will be wonderful, thanks a lot!
If I could maybe retrieve the data from the value field on the switch with a future void but I haven't seen anywhere any answer...
Maybe store your values in a map and then decode/encode them. Like following:
var jsn = prefs.getString('Map');
Map = json.decode(jsn);
var jsn = json.encode(Map);
prefs.setString('Map', jsn);
Let me know if it helps.
Try this for your _getBoolFromSharedPref method.
Future<void> _getBoolFromSharedPref() async {
final prefs = await SharedPreferences.getInstance();
switchbool.length = app.length;
for (var i = 0; i < app.length; i += 1) {
switchbool[i] = prefs.getBool(app[i]) ?? false;
}

How to add dynamic values to field injections list with custom trigger to camunda properties panel?

I have two questions here
Is it possible to add dynamic lists values to field injection list input ?
Can I create a trigger for this so this can be initiated from any other input selection say a class selection will populate all fields
I was just looking into FieldInjection.js whether that can be extented for the same
Can someone please provide a hint or direction for this ?
Thanks.
For anyone interested in the answer, I was able to achieve the above goal by changing the set function of the Java Class select input as folllowing
few imports
var extensionElementsHelper = require('../../../../helper/ExtensionElementsHelper'),
elementHelper = require('../../../../helper/ElementHelper')
var CAMUNDA_FIELD_EXTENSION_ELEMENT = 'camunda:Field';
function getExtensionFields(bo) {
return bo && extensionElementsHelper.getExtensionElements(bo, CAMUNDA_FIELD_EXTENSION_ELEMENT) || [];
}
then changing the set function to create extension element and push the field values as :
set: function(element, values, node) {
var bo = getBusinessObject(element);
var type = getImplementationType(element);
var attr = getAttribute(type);
var prop = {}
var commands = [];
prop[attr] = values.delegate || '';
var extensionElements = getExtensionFields(bo);
//remove any extension elements existing before
extensionElements.forEach(function(ele){
commands.push(extensionElementsHelper.removeEntry(getBusinessObject(element), element, ele));
});
if(prop[attr] !== ""){
var extensionElements = elementHelper.createElement('bpmn:ExtensionElements', { values: [] }, bo, bpmnFactory);
commands.push(cmdHelper.updateBusinessObject(element, bo, { extensionElements: extensionElements }));
var arrProperties = ["private org.camunda.bpm.engine.delegate.Expression com.cfe.extensions.SampleJavaDelegate.varOne","private org.camunda.bpm.engine.delegate.Expression com.cfe.extensions.SampleJavaDelegate.varTwo"]
var newFieldElem = "";
arrProperties.forEach(function(prop){
var eachProp = {
name:"",
string:"",
expression:""
}
var type = prop.split(" ")[1].split(".").reverse()[0];
var val = prop.split(" ")[2].split(".").reverse()[0];
eachProp.name = val;
if( type == "String"){
eachProp.string = "${" + val +" }"
}else if( type == "Expression"){
eachProp.expression = "${" + val +" }"
}
newFieldElem = elementHelper.createElement(CAMUNDA_FIELD_EXTENSION_ELEMENT, eachProp, extensionElements, bpmnFactory);
commands.push(cmdHelper.addElementsTolist(element, extensionElements, 'values', [ newFieldElem ]));
});
}
commands.push(cmdHelper.updateBusinessObject(element, bo, prop));
return commands;
}
Cheers !.

Why does `binary operation argument type newval is not compatible with type string` appear

I have the following code and inside of it the WebStorm inspection Binary operation argument type newVal is not compatible with type string appears:
I'm wondering why
Full module code:
define(function (require) {
"use strict";
var ng = require('angular');
require('../ngModule').directive('downloadFile', ['$parse', 'auth.authService', function ($parse, authService) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var getter = $parse(attrs.downloadFile);
scope.$watch(getter, function (path) {
if (path !== "") {
var form = document.createElement("form");
var element1 = document.createElement("input");
var element2 = document.createElement("input");
form.method = "POST";
form.action = path;
element1.value = authService.getToken();
element1.name = "Authorization";
form.appendChild(element1);
element.append(form);
form.submit();
element.empty();
}
});
}
};
}]);
});
AngularJS's JSDoc definition makes WebStorm think the path argument is a boolean.
You can make WebStorm stop complaining by adding your own JSDoc:
if (path !== /** #type {boolean} */"") {

RegExp in Node Js not working: Cannot call method 'toString' of null

This exact function does not work on Node Js, even though it work fine on a regular browser. How can I make it work on NodeJS?
Example: http://jsfiddle.net/wC53N/
var MyHereDoc = function() {
var bodyEmail = function(){
var test = 1;
/*HEREDOC
<div>
Hola1
<p>
hola2
</p>
</div>
HEREDOC*/
};
var here = "HEREDOC";
var reobj = new RegExp("/\\*"+here+"\\n[\\s\\S]*?\\n"+here+"\\*/", "m");
str = reobj.exec(bodyEmail).toString();
str = str.replace(new RegExp("/\\*"+here+"\\n",'m'),'').toString();
toPrint = str.replace(new RegExp("\\n"+here+"\\*/",'m'),'').toString();
document.getElementById("demo").innerHTML = toPrint;
}
MyHereDoc();
If you try to run this same code on NodeJS u will get this error:
Cannot call method 'toString' of null
But Why? any idea how to make it works, or what am I doing wrong?
Thanks

How do I return data to a template with Knockout and Requirejs modules?

I'm having a difficult time returning data from a module using RequireJS and Knockout to populate my markup for my single page app. Knockout can't seem to find my data binding observables.
I'm trying to keep each view in a separate js file, but I'm failing to identify where I've gone wrong. Here's what I have so far:
/app/app.js
define(function(require) {
require('simrou');
var $ = require('jQuery'),
ko = require('knockout'),
videoView = require('videoView');
var init = function() {
var viewModel = function() {
var self = this;
self.currentPage = ko.observable();
self.videoView = new videoView();
}
var view = new viewModel();
ko.applyBindings( view );
_router = new Simrou({
'/video/:id': [ view.videoView.getVideo ]
});
_router.start();
};
return {
init: init
};
});
/app/videoView.js
define(function(require) {
"use strict";
var $ = require('jQuery'),
ko = require('knockout');
return function() {
var self = this;
self.currentPage = ko.observable( 'showVideo' );
self.currentVideo = ko.observable();
self.videoData = ko.observableArray([]);
self.videoList = ko.observableArray([]);
var getVideo = function( event, params ) {
// ajax pseudo code
$.ajax({});
self.videoData( dataFromAjaxCall );
}
return {
getVideo: getVideo
};
};
});
index.html
When I browse to /#/video/14 I receive the following error:
Uncaught ReferenceError: Unable to parse bindings.
Bindings value: attr: { 'data-video-id': videoData().id }
Message: videoData is not defined
Here's the markup:
<section id="showVideo" data-bind="fadeVisible: currentPage()=='showVideo', with: $root">
<div class="video" data-bind="attr: { 'data-video-id': videoData().id }></div>
</section>
Like I said, I'm trying to keep each view separated, but I would love some enlightenment on what I'm doing wrong, or if this is even possible? Is there a better more efficient way?
videoData is a property of $root.videoView, not of the root model (the one you passed to applyBindings). It's also an observableArray, so videoData() is just a plain array and even if you get the context right, you won't be able to access its id property, since, being an array, it doesn't have.named properties.