NodeJS Cucumber test are executed with not wait - javascript

My test fails. The test is executed immediately, and the automation test doesn't wait to finish some of the actions.
I saw an issue with cucumber and nodejs, but I am unsure how to handle it.
Here is my step js class:
const { Given, When, Then } = require('#cucumber/cucumber');
Given("I visit the automation-practice-form page", async () => {
    await page.goto("https://demoqa.com/automation-practice-form/");
});
When("I fill the form with correct data", async () => {
  await page.fill('#firstName', 'Tester');
    await page.fill('#lastName', 'Testerov');
    await page.fill('#userEmail', 'testingemail#testemail.com');
    await page.check('//*[#id="gender-radio-1"]/following-sibling::label');
    await page.fill('#userNumber', '1232131231');
    await page.click("#dateOfBirthInput");
    await page.click('(//div[#role="option"])[1]');
    await page.fill('#subjectsInput', 'Computer Science');
    await page.keyboard.press("Enter");
    await page.click('//*[#id="hobbies-checkbox-1"]/following-sibling::label');
    await page.setInputFiles("#uploadPicture", "uploads/test-image.jpg");
    await page.fill('#currentAddress', 'Test Address');
    await page.click("#state");
    await page.click('//*[#id="react-select-3-option-1"]', { force: true });
    await page.click("#city");
    await page.click('//*[#id="react-select-4-option-0"]');
});
When("click over the Submit button", async () => {
    await page.click("#submit");
});
Then("I will verify that the data ware filled in correctly", async () =>  {
    let name_actualResultElement = page.locator(
        '//*[contains(text(),"Student Name")]/following-sibling::td'
    );
});
and feature class:
Feature: Fill the form
    As a user
    I want to be able to fill the form
    Scenario: Fill the form with valid data
        Given I visit the automation-practice-form page
        When I fill the form with correct data
        When click over the Submit button
        Then I will verify that the data ware filled in correctly

Related

Shouldn't async functions always execute as the last ones? [duplicate]

This question already has answers here:
Are javascript's async functions actually synchronous?
(2 answers)
When does async function actually return a pending promise?
(1 answer)
Closed 18 days ago.
What's happening here?? the order of execution is commented.
dad() is async and returns a promise. shouldn't it be executed after console.log('faster')?
two() is async w/o await and still it's executes before console.log(5)
g() is awaited and executes as the last one?!
async function dad(){
    async function g(){
    return new Promise((a,b)=>{
    setTimeout(() => {
        console.log('im waiting') //4th
        }, 2000)
        a(6)
    })
    }
    async function two(){
        console.log(2) //1st
    }
    two()
    await g()
    console.log(5) //3rd
}
dad()
console.log('faster') //2nd

autocomplete form in django

i'm trying to make an autocomplete form in django but when i run the page locally don´t run because don't find the url of the json, the idea of the autocomplete is that take information from x table and then the form post the information in y table
views.py
def is_ajax(request):   
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'def
get_employee(request):   
if is_ajax(request=request):       
q = request.GET.get('term', '')       
places = InfoTrabajadores.objects.filter(documento__icontains=q)       
results = []       
for pl in places:           
place_json = {}           
place_json['label'] = pl.state           
results.append(place_json)       
data = json.dumps(results)   
else:       
data = 'fail'   
mimetype = 'application/json'   
return HttpResponse(data, mimetype)
and the jquery
$(document).ready(function() {
async function getCities(event, ui) {
//let url = '{% url ' / api / get_employees / ' %}';
let url = 'http://127.0.0.1:8000/api/get_employees/';
let results = await fetch(url);
let data = await results.json();
return data;
};
async function AutoCompleteSelectHandler(event, ui) {
let zipCode = await getCities();
$('#nombre').val(nombre[ui.item.value]);
$('#num_emergencia').val(num_emergencia[ui.item.value]);
$('#prov_salud').val(prov_salud[ui.item.value]);
$('#prov_salud_trabj').val(prov_salud_trabj[ui.item.value]);
$('#rh').val(rh[ui.item.value]);
};
$("#autoSuggest").autocomplete({
source: "{% url 'invitados' %}",
select: function(event, ui) {
AutoCompleteSelectHandler(event, ui)
},
minLength: 2,
});
});

How to call php function if javascript condition true

I have create some personal project with wordpress + php + google firebase.
I want to execute function if Google firebase OTP verification is success.
Here is the code
function devsol_customer_form() { ?>
<form>
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
<label for="number"><?php esc_html_e( 'Mobile Number', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="tel" class="woocommerce-Input woocommerce-Input--text input-text" name="number" id="number"/>
</p>
<div id="recaptcha-container"></div>
<button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="phoneAuth();">SendCode</button>
</form>
<br/>
<h1>Enter Verification code</h1>
<form>
    <input type="text" id="verificationCode" placeholder="Enter verification code" class="woocommerce-Input woocommerce-Input--text input-text">
    <button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="codeverify();">Verify code</button>
</form>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#config-web-app -->
<script>
    // Your web app's Firebase configuration
    var firebaseConfig = {
    apiKey: "*****",
    authDomain: "*****",
    databaseURL: "*****",
    projectId: "*****",
    storageBucket: "*****",
    messagingSenderId: "*****",
    appId: "*****"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
</script>
<script>
window.onload=function () {
  render();
};
function render() {
    window.recaptchaVerifier=new firebase.auth.RecaptchaVerifier('recaptcha-container');
    recaptchaVerifier.render();
}
function phoneAuth() {
    //get the number
    var number=document.getElementById('number').value;
    //phone number authentication function of firebase
    //it takes two parameter first one is number,,,second one is recaptcha
    firebase.auth().signInWithPhoneNumber(number,window.recaptchaVerifier).then(function (confirmationResult) {
        //s is in lowercase
        window.confirmationResult=confirmationResult;
        coderesult=confirmationResult;
        console.log(coderesult);
        alert("Message sent");
    }).catch(function (error) {
        alert(error.message);
    });
}
function codeverify() {
    var code=document.getElementById('verificationCode').value;
    coderesult.confirm(code).then(function (result) {
        alert("Successfully registered");
        var user=result.user;
        console.log(user);
    }).catch(function (error) {
        alert(error.message);
    });
}    
</script>
<?php }
add_action('woocommerce_after_customer_login_form', 'devsol_customer_form');
I want if user successfully verify the OTP then this function call in my php file. I am using function.php file in my wordpress theme.
function devsol_customer_auth() {
$user_phone = sanitize_text_field( $_POST['number'] );
if ( $user = get_user_by( 'login', $user_phone) ) {
$user_id = $user->ID;
$user_roles = $user->roles;
$user_role = array_shift($user_roles);
if ( $user_role === 'customer') {
if ( apply_filters( 'woocommerce_registration_auth_new_customer', true, $user_id ) ) {
wc_set_customer_auth_cookie( $user_id );
}
}
}
}
add_action('init', 'devsol_customer_auth');
Someone please help
You cannot directly call php function from javascript(JS) as JS runs on the client side like on the browser and your php file exists on the webserver.
In order to do something like that, you'll need to make request to the php file and pass parameter in the request(could be GET or POST).
A simple example of such could be
create a separate php file, lets say actions.php, that will be hit by the request.
make a request to the file from JS
E.g.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
httpGet('www.yourSite.com/actions.php?phone=' + userPhoneNumber);
This should resolve your problem.

JQuery catch any ajax error

i like to catch any ajax 401 Unauthorised exception, but do no like to change all my ajax queries. Is there a way to change it for any $.ajax call like (overwrite any error handler) ?
you can use the global ajax event handlers .ajaxError()
$( document ).ajaxError(function( event, jqxhr, settings, exception ) {
    if ( jqxhr.status== 401 ) {
        $( "div.log" ).text( "Triggered ajaxError handler." );
    }
});
You can do something like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 401) {
alert('HTTP Error 401 Unauthorized.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
This will catch error in any of your ajax calls.
The $.ajaxSetup() function will allow you to specify global options for Ajax calls. Be careful however as other calls to ajaxSetup() will overwrite global options and specified local options to the ajax() method will override global settings.
Documentation
Try using .ajaxError() as a global method http://api.jquery.com/ajaxError/
To catch a 401 status code simply add
$.ajaxSetup({
statusCode: {
401: function(err){
console.log('Login Failed.', err.responseJSON);
// or whatever...
}
}
});
to your page somewhere before the AJAX call is fired.

Buttons within dialog boxes and how to get the respective button value on form submit

I have a razor view which has a form. Within the form there is a button called upload. The upload button posts to an action method which is working fine.
I want to add a modal box confirmation which would appear when they hit upload button, now within the modal box I want to have two buttons. One would say "Normal Parsing" and the other would say "Buffer Parsing". Once they press either button within the dialog box, the form will submit to the action method and within the action method I want to see which dialog button they pressed, either "Normal Parsing" or "Buffer Parsing".
This is what I have so far for the dialog box, I just need to see how will the controller get the value of the button pressed. Thanks guys!!
function getParsingRoute(){
var buttonPressed;
.dialog({
modal: true,
width: 600,
title: 'Parsing Values Confirmation',
buttons: {
"Normal Parsing": function () {
buttonPressed = "Normal";
},
"Buffer Parsing": function () {
buttonPressed = "Buffer
}
}
})
}
#using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
{
<button name="submit" class="art-button" type="submit" value="Upload" onclick="getParsingRoute()" style="width: 100px">Upload</button>
}
Solution inpired by #Barmar comment:
function getParsingRoute(e){
e.stopPropagation();
.dialog({
modal: true,
width: 600,
title: 'Parsing Values Confirmation',
buttons: {
"Normal Parsing": function () {
$("#hiddenInput").val("Normal Parsing");
},
"Buffer Parsing": function () {
$("#hiddenInput").val("Buffer Parsing");
}
}
})
$("#form").submit();
}
#using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
{
<input name="inputName" type="hidden" id="hiddenInput" value="" />
<button name="submit" class="art-button" type="submit" value="Upload" onclick="getParsingRoute()" style="width: 100px">Upload</button>
}
Try something that:
function getParsingRoute(){
var buttonPressed;
.dialog({
modal: true,
width: 600,
title: 'Parsing Values Confirmation',
buttons: {
"Normal Parsing": function () {
$.ajax({
url: "http://example.com",
type: "POST",
data: contactForm.serialize() + "&buttonPresed=Normal Parsing"
}).done(function (data) {
//done
})
},
"Buffer Parsing": function () {
$.ajax({
url: "http://example.com",
type: "POST",
data: contactForm.serialize() + "&buttonPresed=Buffer Parsing"
}).done(function (data) {
//done
})
}
}
})
}
This code only show you way how you can do it.

Categories