I have function which return me application status
getDecision: function() {
browser.wait(protractor.ExpectedConditions.visibilityOf(decisionPage), 60000); // verify the decision and proceed further depending upon it.
element(by.xpath(rejectImage)).isPresent().then(function(result) {
if (result) {
console.log('Application is rejected');
finalResult = 'Rejected';
} else {
element(by.xpath(queueImage)).isPresent().then(function(result1) {
if (result1) {
console.log('Application is sent to underwriter for review');
finalResult = 'Queue';
} else {
console.log('Application is approved');
finalResult = 'Approved';
}
});
}
});
}
Then in same class I am returning the finalResult as :
returnDecision: function() {
console.log('Result is::' + finalResult);
return finalResult;
},
And then in admin portal again I need to take decision based upon status from above function as:
takeDecision: function(testData) {
// Verifying if the case is queued or rejected
if (decision.returnDecision() === 'Queue') {
// Approving the case
if (testData.croDecision.apprvDecision === "Approve") {
// basePage.clickElement(approveButton);
utils.sleep(2);
var approveButton = browser.driver.findElement(By.css(croApproveButton));
approveButton.click();
} else {
var declineButton = browser.driver.findElement(By.css(croDeclineButton));
declineButton.click();
utils.sleep(2);
browser.driver.findElement(By.xpath(remarkDecline)).sendKeys('for testing purpose');
}
utils.sleep(2);
browser.driver.findElement(By.linkText("Submit")).click();
utils.sleep(2);
expect(browser.driver.findElement(By.xpath(decisionSuccessMessage)).isDisplayed()).toBe(true);
} else /*if (decision.returnDecision() === 'Rejected')*/ {
console.log("Case is rejected, no further action");
}
},
and in spec file I am calling this method after I punch a case using user as follow:
fdescribe('Data Entry For Applicant(HL1)', function() {
beforeAll(function() {
this.actionwords = Object.create(require('../actionwords.js').Actionwords);
});
afterAll(function() {
testData.login.username = 'softcellqa1#gmail.com';
//logout of the app
loginPage.logout(testData)
});
fit('test', function() {
testData.loan.existingloan = 'No';
this.actionwords.housingLoanWithoutCoApplicant(testData);
this.actionwords.takeDecision(testData);
});
});
this.actionwords.takeDecision(testData) is always executed before this.actionwords.housingLoanWithoutCoApplicant
Please let me know what is wrong I am doing here?
Related
I am developing a chrome extension where I am injecting a JavaScript script into the active tab when it loads. The code of the script I have attached below. When I use var for declaring myOptions and myGlobals objects, the script runs without any errors. But if I use let for declaring them, then I get syntax error on the first line stating that myOptions has already been declared. I have not even redeclared myOptions and myGlobals objects anywhere in my code. But I have tried to change the values of their properties. I am unable to figure out where I am going wrong. I want to know why let does not work in my code?
var myOptions = {
takeNotes:false,
displayNotes:false
}
var myGlobals = {
displayingForm:false,
tabUrl:window.location.href,
notesCache:[]
}
onloadForeground();
function onloadForeground(){
chrome.storage.sync.get(myGlobals.tabUrl, (data)=>{
myGlobals.notesCache = data[myGlobals.tabUrl]?data[myGlobals.tabUrl].savedNotes:[];
console.log(data);
myGlobals.notesCache.forEach(addSticker);
});
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log(request);
if (request.message === "change_takeNotes_option") {
console.log(`Changing take notes option to ${request.value}`);
myOptions.takeNotes = request.value;
sendResponse({
message:"success"
});
return true;
} else if (request.message === "change_displayNotes_option") {
console.log(`Changing display notes option to ${request.value}`);
myOptions.displayNotes = request.value;
displayNotes();
sendResponse({
message:"success"
});
return true;
} else if (request.message === "save_notes_cache") {
console.log("Saved notes");
saveNotes();
sendResponse({
message:"success"
});
return true;
} else if (request.message === "reset_notes") {
console.log("Reset notes");
resetNotes();
sendResponse({
message:"success"
});
return true;
}
});
function displayNotes(){
const notes = document.getElementsByClassName("note");
console.log(notes.length);
for (let i = 0; i < notes.length; i++) {
notes[i].style.visibility = (myOptions.displayNotes)?"visible":"hidden";
}
}
function saveNotes() {
if (myGlobals.notesCache.length > 0) {
chrome.storage.sync.set({[myGlobals.tabUrl]: {savedNotes:myGlobals.notesCache}});
} else {
chrome.storage.sync.remove(myGlobals.tabUrl);
}
}
function displayForm() {
myGlobals.displayingForm = true;
}
function discardForm() {
setTimeout(() => {
myGlobals.displayingForm = false;
}, 500);
}
function addNote(){
console.log("Adding note");
let noteTitle = document.getElementById("note-inputTitle").value;
let noteDescription = document.getElementById("note-inputDescription").value;
if (noteTitle == null || noteTitle.trim() === "") {
alert("The note requires a title");
} else if (noteDescription == null || noteDescription.trim() === "") {
alert("The note requires a description");
} else {
let note = {
title: noteTitle,
description: noteDescription,
}
myGlobals.notesCache.push(note);
console.log("Current note cache");
console.log(myGlobals.notesCache);
discardForm();
}
}
function discardNote(index) {
myGlobals.displayingForm=true;
setTimeout(()=>{
myGlobals.displayingForm=false;
}, 300);
console.log("Discarding note " + index);
myGlobals.notesCache.splice(index, 1);
console.log("Current note cache");
console.log(myGlobals.notesCache);
}
function resetNotes(){
myGlobals.notesCache = [];
console.log(notesCache);
}
This is the background script I am using to inject the above script
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
console.log(changeInfo);
if (changeInfo.status === "complete" && /^http/.test(tab.url)) {
chrome.scripting.insertCSS({
target: {
tabId: tabId
},
files: ["./foreground.css"]
})
chrome.scripting.executeScript({
target: {
tabId: tabId
},
files: ["./foreground.js"]
})
.then(() => {
console.log("Injected foreground script " + tabId);
chrome.storage.sync.set({ [tabId]: { options:{takeNotes:false, displayNotes:false} } });
})
.catch(err => {
console.log(err);
});
}
});
You use executeScript twice on the same page so when the injected script runs again it tries to declare a let variable in the same context, but this is forbidden by the JavaScript specification.
Solutions:
Keep using var
Wrap the code in an IIFE:
(() => {
// your entire code here
})()
Don't reinject the script twice by adding a condition before executeScript e.g. you can "ping" the tab:
// injected file
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === 'ping') sendResponse(true);
});
// background or popup script
function inject(tabId) {
chrome.tabs.sendMessage(tabId, 'ping', {frameId: 0}, () => {
if (chrome.runtime.lastError) {
// ManifestV2:
chrome.tabs.executeScript(tabId, {file: 'content.js'});
// ManifestV3:
// chrome.scripting.executeScript({target: {tabId}, file: 'content.js'});
}
});
}
Try to check your HTML code. Maybe you included the Javascript code twice. That's the only explanation for the error. I can't see any other error in your code.
I am making a simple validation function that just validates that the props given to the component are not null. When the function runs it gets to the last conditional and logs 'made it' but then also logs '1' which is the else for the first conditional and returns false. I am not sure why its getting to the last conditional and its not returning true. I have also tried using else if statements.
function testValidation(firstOptionWords, secondOptionWords, chooseFirst, chooseSecond) {
if(props.enabled) {
if(firstOptionWords && secondOptionWords) return true;
if(firstOptionWords.length > 0 && secondOptionWords.length > 0) return true;
if(chooseFirst != null && chooseSecond != null) return true;
return false;
}
else {
console.log('Choice is false!')
}
}
const speechRecognizing = async (firstOptionWords, secondOptionWords, chooseFirst, chooseSecond) => {
const results = partialResults.map(function (x) {return x.toLowerCase()});
const matched1 = firstOptionWords.some(options => results.includes(options));
const matched2 = secondOptionWords.some(options => results.includes(options));
const matchedWildCard = partialResults.length > 0 && firstOptionWords.includes('\*');
try {
if(testValidation()) {
await Voice.isRecognizing();
const voiceIsRecognizing = await Voice.isRecognizing();
// TODO run checklists and clean up code, and comment where nessecary. Make sure that all promises are resolved and the library functionality is to design spec.
if(voiceIsRecognizing) {
if(matched1 || matchedWildCard) {
chooseFirst();
stopAndDestroy();
} else if (matched2) {
chooseSecond();
stopAndDestroy();
} else {
stopAndDestroy();
}
} else {
console.log('STARTING');
startRecognizing();
}
} else {
console.log('Validation did not pass')
}
} catch (error) {
console.log(error);
}
}
useEffect(() => {
testValidation(props.firstOptionWords, props.secondOptionWords, props.chooseFirst, props.chooseSecond);
speechRecognizing(props.firstOptionWords, props.secondOptionWords, props.chooseFirst, props.chooseSecond);
}, [partialResults, props.enabled]);
I cannot manage to run WFS-T demos in GeoServer 2.17.2. In Demo always give an error. In a similar way, I want to run WPS demos but always got an error
coverage store not found
In the workspace I enabled WPS but I got no response coming from geoserver side.
HTTP response: 500 Server Error
Anyone know how can I run WFS-T demos in GeoServer ?
// Promises
var _eid_promises = {};
// Turn the incoming message from extension // into pending Promise resolving
window.addEventListener("message", function (event) {
if (event.source !== window) return;
if (event.data.src && (event.data.src === "background.js")) {
console.log("Page received: ");
console.log(event.data);
// Get the promise
if (event.data.nonce) {
var p = _eid_promises[event.data.nonce];
// resolve
if (event.data.result === "ok") {
if (event.data.signature !== undefined) {
p.resolve({
hex: event.data.signature
});
} else if (event.data.version !== undefined) {
p.resolve(event.data.extension + "/" + event.data.version);
} else if (event.data.cert !== undefined) {
p.resolve({
hex: event.data.cert
});
} else {
console.log("No idea how to handle message");
console.log(event.data);
}
} else { // reject
p.reject(new Error(event.data.result));
}
delete _eid_promises[event.data.nonce];
} else {
console.log("No nonce in event msg");
}
}
}, false);
function TokenSigning() {
function nonce() {
var val = "";
var hex = "abcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 16; i++) val += hex.charAt(Math.floor(Math.random() * hex.length));
return val;
}
function messagePromise(msg) {
return new Promise(function (resolve, reject) { // amend with necessary metadata
msg["nonce"] = nonce();
msg["src"] = "page.js";
// send message
window.postMessage(msg, "*");
// and store promise
callbacks _eid_promises[msg.nonce] = {
resolve: resolve,
reject: reject
};
});
}
this.getCertificate = function (options) {
var msg = {
type: "CERT",
lang: options.lang,
filter: options.filter
};
console.log("getCertificate()");
return messagePromise(msg);
};
this.sign = function (cert, hash, options) {
var msg = {
type: "SIGN",
cert: cert.hex,
hash: hash.hex,
hashtype: hash.type,
lang: options.lang,
info: options.info
};
console.log("sign()");
return messagePromise(msg);
};
this.getVersion = function () {
console.log("getVersion()");
return messagePromise({
type: "VERSION"
});
};
}
I need to change the value of the array from 'User' to 'Admin' if the function is clicked on and I have to code it in cloud code.
but there is a problem the array does not change
the following code is working but only the part with nameRoleQuery is not working and that's the part which I need to change.
promoteToAdmin: function promoteToAdmin(request, response) {
if (!request.params.companyUser) {
response.error('Request did not have an authenticated user attached with it');
} else {
var companyUser;
var companyUserQuery = new Parse.Query('CompanyUser');
companyUserQuery.include('user');
companyUserQuery.include('company');
companyUserQuery.get(request.params.companyUser, {
useMasterKey: true
}).then((giveRolename) => {
var nameRoleQuery = new Parse.Query(Parse.Role);
request.nameRoleQuery.set('user', ['Admin']);
return nameRoleQuery.save(null, {
useMasterKey: true
});
}).then((companyUserObject) => {
companyUser = companyUserObject;
var userRoleQuery = new Parse.Query(Parse.Role);
userRoleQuery.equalTo('name', 'Company-User-' + companyUser.get('company').id);
return userRoleQuery.first({
useMasterKey: true
});
}).then((userRole) => {
var usersInUserRole = userRole.relation('users');
usersInUserRole.remove(companyUser.get('user'));
return userRole.save(null, {
useMasterKey: true
});
}).then((userRoleSaveResult) => {
var adminRoleQuery = new Parse.Query(Parse.Role);
adminRoleQuery.equalTo('name', 'Company-Admin-' + companyUser.get('company').id);
return adminRoleQuery.first({
useMasterKey: true
});
}).then((adminRole) => {
var usersInAdminRole = adminRole.relation('users');
usersInAdminRole.add(companyUser.get('user'));
return adminRole.save(null,{
useMasterKey: true
});
}).then((saveResult) => {
console.log('after');
response.success('fissa is aan');
}, (error) => {
console.log(error);
});
console.log();
}
}
the role array needs to change.
Still unsure exactly what you're trying to do, but this is what I imagine you want to happen.
CompanyUser has a pointer called 'user' of type Parse.User. You want to update this Parse.User, based on your image, when you run this query. The following should work:
//AS ABOVE
.then((giveRolename) => {
var user = giveRoleName.get("user");
user.remove('role','user');
user.add('role','admin');
return user.save(null, {useMasterKey:true});
}).then((companyUserObject) => {
//companyUserObject is Parse.User object. If CompanyUser object is needed, store in variable beforehand.
I've put below what I would suggest as an improvement to your current code. It's less sequential and provides greater fallback in an error happens in the middle of the process.
It's without arrow functions, so you'll have to change accordingly.
function promoteToAdmin(request, response) {
var params = request.params;
var companyUserId = params["companyUser"];
var companyUser;
return Parse.Promise.as().then(
function()
{
if(!companyUser)
{
return Parse.Promise.error("Request did not have an user attached with it.");
}
var CompanyUser = Parse.Object.extend("CompanyUser");
var companyUserQuery = new Parse.Query(CompanyUser);
companyUserQuery.include("user");
companyUserQuery.include("company");
return companyUserQuery.get(companyUserId,{useMasterKey:true});
}
).then(
function(fetchedCompanyUser)
{
companyUser = fetchedCompanyUser;
var company = companyUser.get("company");
var userRoleQuery = new Parse.Query(Parse.Role);
userRoleQuery.equalTo('name', "Company-User-" + company.id )
var adminRoleQuery = new Parse.Query(Parse.Role);
adminRoleQuery.equalTo('name', "Company-Admin-" + company.id);
return Parse.Promise.when(
userRoleQuery.first({useMasterKey:true}),
adminRoleQuery.first({useMasterKey:true})
)
}
).then(
function(userRole,adminRole)
{
if(!userRole || !adminRole)
{
return Parse.Promise.error("No role found")
}
var user = companyUser.get("user");
user.remove("role","user");
user.add("role","admin");
userRole.getUsers().remove(user);
adminRole.getUsers().add(user);
return Parse.Promise.when(
user.save(null,{useMasterKey:true}),
userRole.save(null,{useMasterKey:true}),
adminRole.save(null,{useMasterKey:true})
)
}
).then(
function(user,userRole,adminRole)
{
response.success("success");
},
function(error)
{
response.error(error);
}
)
}
Updated: User count before and after signup still failing
Trying to test a new user signing up through the UI (see jQuery "signUp"). Users count from Method.call("usersCount") before and after signup both return 'undefined'.
I see 'undefined' -> user object -> 'undefined' in log. Not sure why user count is not getting assigned to the variable(s) in the spec code.
Second test checking the signup/logged-in users passes.
/tests/jasmine/client/integration/spec.js
// New user signup
function signUp (user, callback) {
$('.dropdown-toggle').trigger('click');
$('#signup-link').trigger('click');
$('#login-username').val(user.username);
$('#login-password').val(user.password);
$('#login-password-again').val(user.password);
$('#login-buttons-password').trigger('click');
callback;
}
describe('User signup', function() {
var user = { username: 'larry', password: 'password' };
beforeEach(function(done) {
Meteor.call("clearDB", done);
});
it('should increase users by one', function (done) {
var userCountBefore = Meteor.call("usersCount");
var userCountAfter = signUp(user, Meteor.call("usersCount"));
expect(userCountBefore + 1).toEqual(userCountAfter);
});
it('should automatically log-in new user', function () {
expect(Meteor.user().username).toEqual(user.username);
});
});
/packages/test-helpers.js (custom debug testing package; clearDB method from [https://gist.github.com/qnub/97d828f11c677007cb07][1])
if ((typeof process !== 'undefined') && process.env.IS_MIRROR) {
Meteor.methods({
usersCount: function () {
var count = Meteor.users.find({}).count();
return count;
},
clearDB: function(){
console.log('Clear DB');
var collectionsRemoved = 0;
var db = Meteor.users.find()._mongo.db;
db.collections(function (err, collections) {
// Filter out velocity and system.indexes from collections
var appCollections = _.reject(collections, function (col) {
return col.collectionName.indexOf('velocity') === 0 ||
col.collectionName === 'system.indexes';
});
// Remove each collection
_.each(appCollections, function (appCollection) {
appCollection.remove(function (e) {
if (e) {
console.error('Failed removing collection', e);
fut.return('fail: ' + e);
}
collectionsRemoved++;
console.log('Removed collection');
if (appCollections.length === collectionsRemoved) {
console.log('Finished resetting database');
}
});
});
});
console.log('Finished clearing');
}
});
};
Ok, this is one way to solve this:
it('should increase users by one', function (done) {
Meteor.call("usersCount", function(error, userCountBefore) {
signUp(user);
Meteor.call("usersCount", function (error, userCountAfter) {
expect(userCountAfter).toEqual(userCountBefore + 1);
done();
});
});
});
Future viewers, checkout the following links for reference/alternate approaches:
https://github.com/caolan/async
https://atmospherejs.com/peerlibrary/async
http://www.html5rocks.com/en/tutorials/es6/promises/
Thanks to #sanjo for helping me see the light!