1

Je suis nouveau à e2e testing (et JS). J'utilise le framework Nightwatch. J'essaye de créer une fonction qui sélectionne un élément aléatoire d'une liste d'éléments avec le même sélecteur, et clique dessus.fonction personnalisée pour sélectionner et cliquer sur un élément aléatoire dans Nightwatch

C'est ce que j'ai essayé:

pickOne(selector, target) { 
    this.api.elements(selector, target, function(res) { 
     optionsLength = Math.floor((Math.random() * res.value.length) + 1); 
    }); 
    this.api.waitForElementVisible(`${target}:nth-child(${optionsLength})`); 
    this.api.click(`${target}:nth-child(${optionsLength}) .action-button`); 
    } 

Mais dans ce cas, optionsLength is not defined.

Math.floor((Math.random() * res.value.length) + 1) renvoie un nombre. Je veux utiliser ce numéro en dehors de la fonction.

J'ai essayé de stocker la fonction complète d'une variable, comme dans:

const optionsLength = this.api.elements(selector, element, function(res) { 
     Math.floor((Math.random() * res.value.length) + 1); 
    }); 

Mais cette façon optionsLength journaux [object Object] place un certain nombre.

Répondre

1

Définir les fonctions 2e et 3e rappel est pas bon, elle conduirait à l'enfer de rappel.

Vous devez utiliser à la place .perform() api, il enchaînera vos fonctions:

pickOne(selector, target) {  
      this.api.elements(selector, target, function(res) { 
       optionsLength = Math.floor((Math.random() * res.value.length) + 1); 
      }) 
      .perform(function (client, done) { 
       console.log(optionsLength) ;// ***you can access optionsLength in above function*** 

       done(); 
      }) 

C'est docs de Nightwatch Perform

0

Déclarer la fonction avec la syntaxe de la flèche et tout envelopper dans le rappel a résolu le problème (portée).

La syntaxe de la flèche permet de continuer à appeler this.api.x dans le rappel.

pickOne(selector, target) { 
    this.api.elements(selector, target, res => { 
     optionsLength = Math.floor((Math.random() * res.value.length) + 1); 
     this.api.waitForElementVisible(`${target}:nth-child(${optionsLength})`); 
     this.api.click(`${target}:nth-child(${optionsLength}) .action-button`); 
    }); 
    } 
-1
function postimgname() { 
var date = new Date(); 
var str =$scope.data_user.user_id + "" +date.getFullYear() + "" + (date.getMonth() + 1) + "" + date.getDate() + "" + date.getHours() + "" + date.getMinutes() + "" + date.getSeconds() 
+ "" + Math.floor(Math.random() * 6) + 1 ; 
return str; 

}