A recent challenge encountered with JavaScript involving incrementation

After successfully resolving my previous issue with the assistance of another user, I'm now encountering a new problem related to the following code snippet:

const faker = require('faker');
const userList = require('./users.json')
var jsonfile = require('jsonfile');
var obj={
    'table':[]
  };

 for (i=0; i <10 ; i++){
   let username = faker.internet.userName();
   let password = faker.internet.password();
   obj.table.push({"id":i,name:username,pass: password});
 }
 jsonfile.writeFile('users.json', obj, {spaces:2}, function(err){
   console.log(err);
 });

 console.log(userList.table);

If I execute the command :

console.log(userList.table[0].name);
console.log(userList.table[0].pass);

The above correctly displays the password, but my objective is to utilize this data by using .type(then the user+ pass) to automate typing those out. To achieve this, I need guidance on how to either move on to the next line automatically [1], or if it's simpler to remove and transfer the data into a new JSON file.

I am implementing this for testing sign-up functionality on a website.

  1. Visit the website and wait for selector
  2. Enter the user and password generated by faker
  3. Retrieve and save the user and password generated by faker in another location
  4. Proceed to the next user and password iteration and repeat the steps

Any assistance would be greatly appreciated,

Thank you!

Answer №1

I am curious about why you are reliant on JSON files, when it might be simpler to work with the existing variables instead.

If you proceed from this point, you can easily iterate over the table array and extract each user's data for input.

const logins = {
  table: []
};

userList.table.forEach(async (user) => {
  const userName = user.name;
  const passWord = user.pass;

  // Assuming how the page is loaded
  await loadPageAndWaitOnSelector();

  userSelector.type(userName);
  passSelector.type(passWord);

  // Check if the login was successful before saving
  await loginSuccessFull();

  logins.table.push(user);

  // Write the data to a new file after each login
  jsonfile.writeFile('logins.json', logins, {spaces:2}, function(err){
     console.log(err);
  });
})

At the end, you will have two JSON files with identical content. If you wish to differentiate between successful and unsuccessful logins, an additional condition can be added around the saving process.

In-memory approach

You could integrate your code with the one above to generate fake data on-the-fly.

const faker = require('faker');
const jsonfile = require('jsonfile');

/**
 * Generates a username and password tuple
 */
const generateUserLogin = () => ({
  userName: faker.internet.userName(),
  passWord: faker.internet.password()
})

/**
 * A reducer function that tests logins and categorizes them as successes or failures
 */
const loadPageAndLogin = async (logins, credentials) => {
  const acc = await logins;

  const {userName, passWord} = credentials;

  // Assumed page loading process
  await loadPageAndWaitOnSelector();

  userSelector.type(userName);
  passSelector.type(passWord);

  const isSuccess = await loginSuccessFull();

  if (isSuccess) {
    acc.success.push(credentials);
  } else {
    acc.failure.push(credentials);
  }

  return acc;
}

// Creating 10 entries of empty arrays
const logins = [...Array(10)]
  .map(generateUserLogin)
  .reduce(loadPageAndLogin, Promise.resolve({success: [], failure: []}))

// Saving the resulting data into a new file
jsonfile.writeFile('logins.json', logins, {spaces:2}, function(err){
    console.log(err);
});

This example generates only a single JSON file for the results, separating successful and failed logins within it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve information from a database in real-time using Ajax without needing to set a refresh interval

Currently, I have been working on jquery/ajax requests and have managed to create an ajax request that retrieves data from a database. However, the issue at hand is that I am continuously utilizing window.setInterval() to refresh this function every x seco ...

A practical method for restructuring or dividing a string containing JSON entries

Within my dataset, I've got a string comprising JSON entries linked together similar to the following scenario. val docs = """ {"name": "Bilbo Baggins", "age": 50}{"name": "Gandalf", "age": 1000}{"name": "Thorin", "age": 195}{"name": "Balin", "age" ...

Utilizing TypeORM to selectively choose data in OneToMany relationships

I am looking to create a TypeORM query that pulls data from the database. Specifically, I want to retrieve all clients who have made a purchase but have not initiated a return. Here is the structure of the database: Clients: Id (Int, primary column) Purc ...

The challenges with implementing makeStyles in React Material UI

const useStyles = makeStyles((theme) => ({ toolbarMargin: { ...theme.mixins.toolbar, marginBottom: "3em", }, logo: { height: "7em", }, tabContainer: { marginLeft: "auto", }, tab: { ...theme ...

Serve static files from parent directories using Express.js

Currently facing some issues serving static files with expressJs. Directory structure: public css lib src views home index.html server.js In my index.html, all assets are prefixed with a leading slash. Static file setup: app.use(express.static ...

Leveraging the same React component in multiple instances and streamlining requests - NextJS vs React

Currently, I'm working on a chat application using NextJS 14. Each time a message is sent or received, there is a small icon next to the chat message that represents the user who sent the message. To achieve this, I have a ChatMessageUI component tha ...

Toggling markers according to form selections is not functioning

My goal is to dynamically show or hide markers on my Google Map that represent houses and condos, based on the features selected by the user from a select box with id #features. For example, if a user picks 'Swimming Pool' as a feature and click ...

What are the steps to leverage npm installed packages in my .js files?

I'm new to web development and I'm trying to incorporate node packages into my workflow. Specifically, I'm attempting to test out the axios ajax library. It seemed like this would be a simple task, but it's proving to be quite challeng ...

The on() method in jQuery is failing to work on an element that has a class added dynamically

After adding an active class to a link once a product is added to cart, I tried using that class to determine the function of the link. However, the on() click event on the link does not trigger unless the page is reloaded. Below is the code snippet where ...

Bundling extraneous server code in client rollup

Can someone help me understand why the following code is being included at the top of my browser bundle by Rollup? It seems like these references are not used anywhere from my entry point. Could it be default includes from node builtins? import require$$0$ ...

What are some methods for extracting data from unidentified JSON files?

I am currently working with a JSON file that has been generated by an API. The contents of the file are as follows: { "johnDoe": { "id": 39464441, "name": "John Doe", "profileIconId": 558, "summonerLevel": 3 ...

"ExceptionThrownByMoveTargetOutOfBounds in Selenium WebDriver for IE9 and Firefox

Having trouble with the FireFox/IE9 driver in Selenium? When using the Actions class and its moveToElement method, I keep encountering a MoveTargetOutOfBoundsException error. Despite trying different solutions like Coordinates, Point, and javascriptexecuto ...

Ensure that only one menu with a specific class is open at any given time

My goal is to ensure that both menus cannot be open simultaneously. The desired behavior is as follows: When one menu is already open and you click on another, the first one should automatically close. For a better understanding of what I am trying to achi ...

Issue with interaction between jQuery AJAX and PHP login functionality

Currently, I am attempting to implement an inline login feature that triggers whenever the PHP $_SESSION['logged_in'] variable is not defined (this variable gets set when a user logs in). The challenge arises when I try to keep the user on the sa ...

angularJS transformRequest for a specified API call

Looking for a way to pass multipart/formdata through a $resource in Angular so I can post an image. I discovered a helpful solution on this Stack Overflow thread. However, the solution applies to all requests within my modules, and I only want it to apply ...

Guide to choosing and unchoosing a div / button using angularJs

I am attempting to create a functionality where items are displayed in a div instead of a list. When an item is clicked, the background color of the div changes and the item is added to a column. Clicking on the item again will revert it back to its origin ...

What is the best way to have child divs occupy the entire area of the parent div while also accounting for margins

I am facing a challenge with arranging child divs inside a parent div that has a specific width. Even though I am using isotope to arrange them, the layout modes do not work well for me in terms of spacing. My goal is to have the child divs fill the space ...

Removing shapes from a PDF using Python

In my current setup, students are able to submit PDF files which the teacher can then annotate using the Adobe Embed API. This feature is extremely helpful as it allows the teacher to easily add and remove comments on the PDF. However, there is a scenario ...

What is the method for setting a border radius for an infowindow on a Google Map

I'm working with a Google Map InfoWindow and I need to set a border radius for it. Can anyone provide some guidance on how to accomplish this? Below is the code I am currently using: var latlng = new google.maps.LatLng(lat,lng); var myOptions = ...

Having trouble fetching JSON on the server (NodeJs) as I keep receiving the error "Unexpected Token U in position 0"

I have gone through several posts on dealing with sending and retrieving JSON using NodeJs and Express, but I am still struggling to make it work. Someone mentioned that the issue might be due to invalid JSON. var arr = { City: 'someplace', Coun ...