Is it possible to create a file with all my functions and read from from it in my specs? - protractor

I have some specs that are using the same functions, I would like to make one single file only for functions and read from this file while executing my scripts, would be that possible? if so.. how to do that?
During google searchers I found the "exports" to add in config file but didn't work (also I don't know how to call it from the config)
For example, I would like to add 2 functions in my config file (or separated file only for functions) and during any point of my execution, call it from the spec file:
function loginAdminUser(userElement, passWordElement, userName, password){
var loginButton = element(by.id('logIn'));
browser.get('https://( ͡° ͜ʖ ͡°).com/');
userElement.sendKeys(userName);
passWordElement.sendKeys(password);
loginButton.click();
}
function accessHistoryViewDetail(){
menuForViews.then(function(selectview) {
selectview[3].click();
browser.sleep(500);
});
}
1 - How can I do that? (using "Suites" would be an option?)
2 - How to call them in my specs?
Thank you and have a good day!

As far as I know you cannot add utility functions that you want to use in your tests in the config file. The options in the config file are generally for setting up the testing environment.
You can however put your functions in a separate file and import that to use the functions. Below is an example of how to do that using js and Node's module exports, you can do something similar with ts using classes.
// utils.js
function loginAdminUser(userElement, passWordElement, userName, password){
var loginButton = element(by.id('logIn'));
browser.get('https://( ͡° ͜ʖ ͡°).com/'); // nice Lenny face :)
userElement.sendKeys(userName);
passWordElement.sendKeys(password);
loginButton.click();
}
function accessHistoryViewDetail() {
menuForViews.then(function(selectview) {
selectview[3].click();
browser.sleep(500);
});
}
module.exports = {
loginAdminUserloginAdminUser: loginAdminUser,
accessHistoryViewDetail: accessHistoryViewDetail
}
Then in your spec file
import * as utils from './utils.js';
...
it('should ...', () => {
...
utils.accessHistoryViewDetail();
...
});
});
I hope that helps.

Related

VSCode API check if path exists

In a VSCode extension, how can I check if a file path exists without opening or reading the file?
The closest thing I've found are vscode.workspace.fs.Readfile and vscode.workspace.openTextDocument (https://code.visualstudio.com/api/references/vscode-api#FileSystem), but again, I do not want to open or read the file. Is there a way to do this?
Per #realappie's comment on another answer, you can use vscode.workspace.fs.
It doesn't have a method like exists, but you can use .stat() for that. An example from the repo:
try {
await vscode.workspace.fs.stat(jsUri);
vscode.window.showTextDocument(jsUri, { viewColumn: vscode.ViewColumn.Beside });
} catch {
vscode.window.showInformationMessage(`${jsUri.toString(true)} file does *not* exist`);
}
There is no API for that because there is a builtin function:
import * as fs from 'fs'; // In NodeJS: 'const fs = require('fs')'
if (fs.existsSync(path)) {
// File exists in path
}

reference sails config outside module.exports

How can I use sails.config outside the module.exports? I'm trying to pass sails.config variables to another object, something like below;
var foo = new Foo(sails.config.myconf.myVar);
module.exports {
bar : function(){
// Use foo here
foo.blah();
}
};
(Same question also asked in a comment in this Create config variables in sails.js? See #jreptak comment)
Each files of Sails config is a module then if you want to use it, you just have to import it.
Here is an example to import Sails connections of sails.config.connections module.
Be careful about the path of the module in the require, it must be relative.
var connections = require('../../config/connections');
This was not possible in Sails v0.9. However, this is now possible in Sails v0.10 onwards.
Here's the specific issue on github: https://github.com/balderdashy/sails/issues/1672
So now you can do something like this:
//MyService.js
var client = new Client(sails.config.client);
module.exports = {
myMethod: function(callback){
client.doSomething();
}
}
If you're stuck with Sails v0.9, I would recommend that you follow the workaround specified in the github issue:
//MyService.js
var client;
module.exports = function(){
client = client || new Client(sails.config.client);
return {
myMethod: function(){
client.doSomething();
}
}
}
Which can be used like so:
//SomeController.js
module.exports = {
list: function(req,res){
MyService().myMethod();
}
}
You can't do this, if you want to access sails.config params you have to create a custom hook http://sailsjs.org/documentation/concepts/extending-sails/hooks and do your 'magic' in it

Is there a way to create and run a dynamic script from karma.conf.js

I'm using karma to run tests on an angularjs application.
There are a couple JavaScript functions that I would like to run at start-up, but they need to be dynamically created based on some system data. When running the app, this is handled with node.
Is there any way to create a script as a var and pass it to the files: [] rather than just using a pattern to load an existing file?
I can make this work by creating the file, saving it to disk then loading it normally, but that's messy.
You can create your own karma preprocessor script.
For a starting point use the following as example:
var fs = require('fs'),
path = require('path');
var createCustomPreprocessor = function (config, helper, logger) {
var log = logger.create('custom'),
// get here the configuration set in the karma.conf.js file
customConfig = config.customConfig || {};
// read more config here in case needed
...
// a preprocessor has to return a function that when completed will call
// the done callback with the preprocessed content
return function (content, file, done) {
log.debug('custom: processing "%s"\n', file.originalPath);
// your crazy code here
fs.writeFile(path.join(outputDirectory, name), ... , function (err) {
if (err) {
log.error(err);
}
done(content);
});
}
};
createCustomPreprocessor.$inject = ['config', 'helper', 'logger'];
module.exports = {
'preprocessor:custom': ['factory', createCustomPreprocessor]
};
Add a package.json with the dependencies and serve it as a module. ;)
For more examples have a look to more modules here: https://www.npmjs.org/search?q=karma%20preprocessor

How to add custom javascript code to validate field in contacts module in sugarcrm

I want custom code to be made on onblur of first_name field in sugarcrm.
The code should also be upgrade safe.
Please help!
Copy modules/Contacts/metadata/editviewdefs.php
into
custom/modules/Contacts/metadata/editviewdefs.php
(if it does not already exist. If so, use the existing one)
All your changes in this file are upgrade safe. Now open your new file, and you'll see one big array containing everything that's in the EditView of the Contacts-module.
Add the following inside the "templateMeta" array, for instance, right after "form".
'includes'=> array(
array('file'=>'custom/modules/Contacts/EditView.js'),
),
This includes the file custom/modules/Contacts/EditView.js, in which you are free to write all the javascript you feel like!
Remember to do a Quick Repair & Rebuild when you are done.
I don't know which version of SugarCRM you uses, but in SugarCRM 7, the following works:
Create a file 'record.js' in /custom/modules/Contacts/clients/base/views/record/. In that file, you can add custom validation.
Some code you could use is:
({
extendsFrom: 'YourModuleRecordView',
initialize: function (options) {
app.error.errorName2Keys['field_error'] = 'This is an error message';
this._super('initialize', [options]);
this.model.addValidationTask('check_field', _.bind(this._doValidateField, this));
},
_doValidateField: function(fields, errors, callback) {
if (this.model.get('myField') .... ) {
errors['myField'] = errors['myField'] || {};
errors['myField'].field_error = true;
}
callback(null, fields, errors);
}
});
Don't forget to change the fields names like you named them!
This result is only for edit mode. To add this validation to the creation mode, add the file 'create_actions.js' to /custom/modules/Contacts/clients/base/views/create_actions/
Enter the folling code in your 'create_actions.js':
({
extendsFrom: 'CreateActionsView',
initialize: function (options) {
app.error.errorName2Keys['field_error'] = 'Thsis is an error message';
this._super('initialize', [options]);
this.model.addValidationTask('check_field', _.bind(this._doValidateField, this));
},
_doValidateField: function(fields, errors, callback) {
if (.....) {
errors['myField'] = errors['myField'] || {};
errors['myField'].field_error = true;
}
callback(null, fields, errors);
}
});
Perform a repair/rebuild when you added this files with the right code.
You can customize this code to your own needs.

require.js synchronous loading

I'd like to define a module which computes a new dependancy, fetches it and then returns the result. Like so:
define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
var name = get_config_name();
var config;
require.synchronous([configs / '+name'], function(a) {
config = defaults.extend(a);
});
return config;
});
Is there a way to do this or a better way to attack this problem?
You may try to use synchronous RequireJS call require('configs/'+get_config_name()), but it will load a module synchronously only if it is already loaded, otherwise it will throw an exception. Loading module/JavaScript file synchronously is technically impossible.
UPD: It's possible (see Henrique's answer) but highly unrecommended. It blocks JavaScript execution that causes to freezing of the entire page. So, RequireJS doesn't support it.
From your use case it seems that you don't need synchronous RequireJS, you need to return result asynchronously.
AMD pattern allows to define dependencies and load them asynchronously, but module's factory function must return result synchronously. The solution may be in using loader plugin (details here and here):
// config_loader.js
define(['defaults', 'get_config_name'], function(defaults, get_config_name) {
return {
load: function (resourceId, require, load) {
var config_name = 'configs/' + get_config_name();
require([config_name], function(config) {
load(defaults.extend(config));
})
}
}
});
// application.js
define(['config_loader!'], function(config) {
// code using config
});
If get_config_name() contains simple logic and doesn't depend on another modules, the better and simpler is calculating on the fly paths configuration option, or in case your config depends on context - map configuration option.
function get_config_name() {
// do something
}
require.config({
paths: {
'config': 'configs/' + get_config_name()
}
});
require(['application', 'defaults', 'config'], function(application, defaults, config) {
config = defaults.extend(config);
application.start(config);
});
Loading JavaScript synchronously is NOT technically impossible.
function loadJS(file){
var js = $.ajax({ type: "GET", url: file, async: false }).responseText; //No need to append
}
console.log('Test is loading...');
loadJS('test.js');
console.log('Test was loaded:', window.loadedModule); //loadedModule come from test.js