问题
So I have created a js array for a list of postcodes. The array is as below in the code: -
//postcode.js file
var postcode = [
"b28 8ND",
"b49 6BD",
"b28 0ST",
"b31 4SU",
"B92 9AH",
];
What I need to do is in my test randomly select a postcode for this js file to enter into a text field when running my automation tests. How do I go about doing this? An example would be much appreciated as I can't find much on the internet & I'm quite new to TestCafe & javascript. Below is what I have in my test file: -
//test.js file
.click(page.create.withAttribute('mattooltip', 'Create job'))
At this point I need to randomly select 1 of the postcodes from the postcode.js file
回答1:
Since "postcode" is an array, you can generate a random index as shown below:
var s = 55;
var random = function() {
s = Math.sin(s) * 10000;
return s - Math.floor(s);
};
//...
var postIndex = Math.floor(random() * postcode.length);
var currentPost = postcode[postIndex];
For example:
import { Selector } from 'testcafe';
fixture `Getting Started`
.page `http://devexpress.github.io/testcafe/example`;
const postcode = [
"b28 8ND",
"b49 6BD",
"b28 0ST",
"b31 4SU",
"B92 9AH",
];
var s = 55
var random = function() {
s = Math.sin(s) * 10000;
return s - Math.floor(s);
};
test('My first test', async t => {
var postIndex = Math.floor(random() * postcode.length);
var currentPost = postcode[postIndex];
console.log(currentPost)
await t
.typeText('#developer-name', currentPost);
});
回答2:
As far as I understood you want to pick a random element from your array
var arr = ['a', 'b', 'c', 'd'];
let randomIndex = Math.floor(Math.random() * arr.length );
alert(arr[randomIndex])
If i am wrong and this is not what you want, please edit your post and explain your question a little bit better
来源:https://stackoverflow.com/questions/51303283/how-do-i-use-an-array-ive-created-within-my-test-file