How to freeze request to test that components are disabled using Cypress?

I’m using VueJS and Cypress to test the app e2e. I have a modal where user fills a form and click on the “send” button. When user clicks on that button, we disable the form fields and the button so the user won’t be able to fill/click them. After that we perform a POST request to upload the data and when it’s done, we enable again (and close the modal). The method which does it:

    updateUIComponents: function(status) {
      this.field.disabled = status;
      ...
      this.sendButtondisabled = status;
    },

I want to test if those components are actually disabled, using Cypress. But the problem is that I can’t seem to figure how can I “freeze” the post request and check if it’s disabled. My current code looks like:


it('Test', () => {
    cy.intercept('GET','**/api/get-data', {
      statusCode: 200,
      fixture: 'test_input_one_record.json'
    });
    cy.intercept('POST','**/api/update-data', {
      statusCode: 200,
      fixture: 'test_input_no_data.json'
    }).as('updateData');
    cy.visit("http://localhost:8080");
    cy.get('tbody tr').eq(0).find('td').eq(8).find('button').click();           // Open modal
    cy.get('div[role="dialog"]').find('button').eq(1).click();                  // Click on update button
    cy.get('@updateData').then((interception) => {                              // Check form data parameters 
      assert.isNotNull(interception);
      const values = parseDataRequest(interception.request);
      assert.isTrue(values.data_number === "2222");
    });
});

How can I make the cy.get('div[role="dialog"]').find('button').eq(1).click() “wait”? The way I can check if it’s disabled:

cy.get('#edit-document-data-number').find('input').should('be.disabled');

async function not returning value

I am trying to return buildings and access it in the promise at the bottom of the script, but it seems like the console.log in the then part of the promise is executing before the getRecord function finishes, and so I can’t access the array I am creating.

async function getRecords() {
     const buildings =[]
     data =updateTable.select({
        fields:['building_name']
    }).eachPage(function page(records, fetchNextPage){
        
        records.forEach(function(record){
            num++
            //console.log(num)
            try{
             //console.log(record['fields']['building_name'])
             
             buildings.push(record['fields']['building_name'])
            }
            catch(err){
                console.log('hello1')
                console.log(err)
            }

        }) 
            try{
        fetchNextPage()
            }
            
            catch{
                console.log('hello2')
                return buildings;
            }
    },function (err) {
        console.log(err)
        console.log('hello3')
        if (err) {
            console.log('errror')
            console.log(err);
            return;
        }
        console.log('hello4')
        console.log(buildings)
        console.log('hello5')
        return buildings
           
    });   console.log('hello6')
    }




getRecords().then(function(r){
    console.log('test')
    console.log(r)
})

Data table not rendering from firebase

New to working with firebase.

The format of my database is as follows

L1
--L2
---L3
----L4
------- Result 1
------- Result 2
------- Result 3
------- Result 4
----L4
------- Result 1
------- Result 2
------- Result 3
------- Result 4

I am trying to simply render the data on my front end via React, but nothing is rendering when calling in the data table component. In-fact, the whole application does then not render, simply a white screen.

Below is the component for the data table, which I am trying to render.

Where am I going wrong when trying to render the data?

const Data = () => {
    const [data, setData] = useState ({});
    useEffect (() => {
        Database.child("L1").on("value", (snapshot) => {
            if (snapshot.val() !== null) {
                setData({ ...snapshot.val() });
            } else {
                setData({});
            }
            });

        return () => {
            setData ({});

        };
    }, []);
    return (
        <div style={{marginTop: "100px"}}>
           
                <table className="styled-table">
                    <thead>
                        <tr>
                            <th style={{textAlign: "center"}}> L4 </th>
                            <th style={{textAlign: "center"}}> L4 </th>
                         
                        </tr>
                    </thead>
                    <tbody>
                        {Object.keys(data).map((id, index) => {
                            return (
                                <tr key={id}>
                                <th scope="row">{index +1}</th>
                                <td>{data[id].result_1}</td>
                                <td>{data[id].result_2}</td>
                                <td>{data[id].result_3}</td>
                                <td>{data[id].result_4}</td>


                                </tr>
                            )
                        } )}
                    </tbody>
                </table>
          
        </div>
    );
};

export default Data

react-native-screens: compileDebugKotlin Error

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ‘:react-native-screens:compileDebugKotlin’.

Error while evaluating property ‘filteredArgumentsMap’ of task ‘:react-native-screens:compileDebugKotlin’
Could not resolve all artifacts for configuration ‘:react-native-screens:debugCompileClasspath’.
> Failed to transform core-ktx-1.5.0.aar (androidx.core:core-ktx:1.5.0) to match attributes {artifactType=android-classes-jar, org.gradle.category=library, org.gradle.dependency.bundling=external, org.gradle.libraryelements=aar, org.gradle.status=release, org.gradle.usage=java-api}.
> Execution failed for AarToClassTransform: C:UsersABC.gradlecachestransforms-3186e662719f643b770233b2443ab0f39transformedjetified-core-ktx-1.5.0.aar.
> zip END header not found

  • Try:
    Run with –stacktrace option to get the stack trace. Run with –info or –debug option to get more log output. Run with –scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 28s

at makeError (D:ReactNativetodonode_modulesexecaindex.js:174:9)
at D:ReactNativetodonode_modulesexecaindex.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (D:ReactNativetodonode_modules@react-native-communitycli-platform-androidbuildcommandsrunAndroidrunOnAllDevices.js:109:5)  
at async Command.handleAction (D:ReactNativetodonode_modules@react-native-communityclibuildindex.js:192:9)

info Run CLI with –verbose flag for more details.
please help me out with this

Trying to fade out a CSS transition

I have this simple page transition where after clicking a button 3 images slide out and you’re taken to a different page. Everything works fine except the last image stays there for the duration I specify using setTimeout and disappears instantly once the time is up, revealing the new page. I need it to fade out instead. I tried using CSS @keyframes and it works only without the JS, for example if I set the animation-fill-mode to “forwards” and fade out of it. However I need to use JS to link to the other page after the transition. Another thing I’ve tried is using jQuery (both with and without setTimeout) but in both cases it just gets stuck on the last image and doesn’t link to the new page. Here it is (apologies, couldn’t figure out how to insert 2 separate codes).

const link = document.querySelector('.link');
const transition = document.querySelector('.transition');
link.addEventListener('click', (e) => {
 e.preventDefault();
 transition.classList.add('slide')
 $('body').fadeOut('slow', function() {
 window.location = link.href;
});
});


And here's the full original code, simplified. 

<!DOCTYPE html>
<html>
<head>
<style> 

.cover {
width: 100vw;    
height: 100vh;
position: fixed;
top: 0;
left: -100vw;
z-index: 100;
opacity: 1;
}

.transition.slide .cover1 {
background: red;
animation: slide 0.3s ease-in-out forwards;
opacity: 1;
}

.transition.slide .cover2 {
background: green;
animation: slide 0.3s ease-in-out forwards;
animation-delay: 0.3s; 
opacity: 1;
}

.transition.slide .cover3 {
background: blue;
animation: slide 0.3s ease-in-out forwards;
animation-delay: 0.6s;
opacity: 1;
}


@keyframes slide {
 from {left: -100vw; }
 to {left: 0; }
}


</style>
</head>
<body>


<div class="transition">
<div class="cover cover1"></div>
<div class="cover cover2"></div>
<div class="cover cover3"></div>
</div>

<a class="link" href="./index5.html">Contact</a>

<script>
const link = document.querySelector('.link');
const transition = document.querySelector('.transition');
link.addEventListener('click', (e) => {
 e.preventDefault();
 transition.classList.add('slide')
 setTimeout(() => {
   window.location = link.href;
 }, 3700);
});
</script> 

</body>
</html>

How to check HTTP Status Code of dynamically added *.js

for a project I need to check the Response Code of a dynamically added JS into DOM. So Code looks basically like this one:

var newScript = document.createElement("script");
newScript.src = "http://www.example.com/dynamic-XXX.js";
target.appendChild(newScript);

The XXX will change and I am loading the File from Google Cloud Storage. So if I have a 200, everything is fine. But I need to check if I have 201 Status Code.

Any Ideas how to solve this in a nice way ?

Convert Server Time Into Visitors’ Local Time in WordPress

I am a newbie in WordPress and Web Development, so please bear with me.

I have a WordPress website which shows data of schedules and results of football matches every single day.

I use shortcodes produced by a plugin to present the data received from API in each pages of my website. And everything is presented nicely.

The problem is the time of the football matches showed in the website is static and purely based on my WordPress’ server time.

I want the visitors to see the time of the matches based on their own local time/timezone.

Is it possible to achieve this in PHP or JavaScript?

Any help would be greatly appreciated.

how to add user data javascript

I am having trouble being able to add user input data. I can get it working when I add in the data myself all the users show up in the console in the array. For people 1-3 I would like them to enter their name and favorite color but I can’t seem to be able to store it or at least have it come up in the console. I did remove person 2 and 3 from the array so I can test it easier and quicker. if you were to take the

    user: document.getElementById('name').value,
    color: document.getElementById('color').value,

and all the comments it would work and show up in console how i want it to but cant seem to do user data. Sorry if this is confusing i am a new to javascript.

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <form>
        <div class="formBox">
            <label for="name">Name</label>
            <input type="text" id="name" placeholder="Name"/>
        </div>


        <div class="formBox">
            <label for="color">Favorite color</label>
            <input type="text" id="color" placeholder="Color"/>
        </div>

        <div class="formBox">
            <button id="btn">Click to Add</button>
        </div>
        <div id="msg">
            <pre></pre>
        </div>
    </form>
    

    <script >


const person1 = {
    user: document.getElementById('name').value,
    color: document.getElementById('color').value,

   /* user: "Sarah",
    color: "Yellow",*/
  };


  /* const person2 = {
    user: "Aaron",
    color: "Yellow"
  };
  
  const person3 = {
    user: "Sarah",
    color: "Green",
  };
  */
  array = [person1]
  
  sort = array.sort(function(a, b){
      if(a.user < b.user) { return -1; }
      if(a.user > b.user) { return 1; }
      return 0;
  })
  
  console.log(sort)



    </script>
</body>
</html>

Setting a Property of an Object in Array 1 based on Value from Array 2

I have two arrays here. Array 1 is an array of arrays consisting of some objects as follows:

var house = [
  [
    { x: 50, y: 50, selected: false },
    { x: 150, y: 50, selected: false },
    { x: 250, y: 50, selected: false },
    { x: 350, y: 50, selected: false },
    { x: 450, y: 50, selected: false },
    { x: 550, y: 50, selected: false },
    { x: 650, y: 50, selected: false },
    { x: 750, y: 50, selected: false },
    { x: 850, y: 50, selected: false },
    { x: 950, y: 50, selected: false },
  ],
  [
    { x: 50, y: 130, selected: false },
    { x: 150, y: 130, selected: false },
    { x: 250, y: 130, selected: false },
    { x: 350, y: 130, selected: false },
    { x: 450, y: 130, selected: false },
    { x: 550, y: 130, selected: false },
    { x: 650, y: 130, selected: false },
    { x: 750, y: 130, selected: false },
    { x: 850, y: 130, selected: false },
    { x: 950, y: 130, selected: false },
  ]
]

And array 2 consisting of some boolean values

var isSelected = [
  false,
  false,
  false,
  false,
  false,
  false,
  true,
  false,
  false,
  false,
  true,
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  true,
  false
]

How can I iterate over these arrays so that if the value of any element in array 2 is true, then I must set the value of the property “selected” of the object in the corresponding array in array 1 to true as well?

How to optimize chart data | ChartJS

My question is about chartJS.
I have Chart type line with 2 datasets the data is about members evrey 3 minutes in 24 hour.
The thing is that its a lot of data about 1500 rows of sql table.
The problem im getting with is that because there is alot of data the chart is looking awful.
My question is there is any way how can I optimize it so it will look better?

The Chart

The chart is based on ChartJS
This is the code of the chart settings –

 Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#292b2c';

// Area Chart Example
var ctx = document.getElementById("myAreaChart");
var myLineChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: <?php echo json_encode($cnnlsTime) ?> ,
    datasets: [
        {
      label: "CNNls Members",
      lineTension: 0.1,
      backgroundColor: "rgba(255,165,0,0.2)",
      borderColor: "rgba(2,117,216,1)",
      pointRadius: 1,
      pointBackgroundColor: "rgba(2,117,216,1)",
      pointBorderColor: "rgba(255,255,255,0.8)",
      pointHoverRadius: 2,
      pointHoverBackgroundColor: "rgba(2,117,216,1)",
      pointHitRadius: 50,
      pointBorderWidth: 2,
      data: <?php echo json_encode($cnnlsMembers) ?> ,
    },
   
    {
      label: "CNNSF Members",
      lineTension: 0.1,
      backgroundColor: "rgba(255,165,0,0.2)",
      borderColor: "rgba(2,117,216,1)",
      pointRadius: 1,
      backgroundColor: "rgba(2,117,216,1)",
      pointBorderColor: "rgba(255,255,255,0.8)",
      pointHoverRadius: 2,
      pointHoverBackgroundColor: "rgba(2,117,216,1)",
      pointHitRadius: 50,
      pointBorderWidth: 2,
      data: <?php echo json_encode($cnnsfMembers) ?> ,
    },
],
  },
  options: {
    scales: {
      xAxes: [{
        time: {
          unit: 'time'
        },
        gridLines: {
          display: false
        },
        ticks: {
          maxTicksLimit: 400
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 30,
          maxTicksLimit: 5
        },
        gridLines: {
          color: "rgba(0, 0, 0, .125)",
        }
      }],
    },
    legend: {
      display: false
    }
  }
});

Any suggestions?

API Images not displaying and card not dynamically populated

I am trying to display Unsplash images on cards.

The cards are created using JavaScript.

The 10 objects from the Unsplash API is shown on the console.

However, I cannot seem to find the problem on why the cards and the API Unsplash images are not displaying.

Appreciate any help, thanks.

https://jsfiddle.net/r3egLqph

const resultsNav = document.getElementById('resultsNav');
const favouritesNav = document.getElementById('favouritesNav');
const imagesContainer = document.querySelector('.images-container');
const saveConfirmed = document.querySelector('.saveConfirmed');
const loader = document.querySelector('.loader');


// Unsplash API
const count = 10;
const apiKey = 'DEMO KEY';
const apiUrl = `https://api.unsplash.com/photos/random?client_id=${apiKey}&count=${count}`;

let resultsArray = [];

function updateDOM() {
  resultsArray.foreach((result) => {
    // Card Container
    const card = document.createElement('div');
    card.classList.add('card');
    // link
    const link = document.createElement('a');
    link.href = result.hdurl;

    //Images
    const image = document.createElement('img');
    image.src = result.url;
    image.alt = 'Image';
    image.loading = 'lazy';
    image.classList.add('card-img-top');
    //Card Body
    const cardBody = document.createElement('div');
    cardBody.classList.add('card-body');
    // Save Text
    const saveText = document.createElement('p');
    saveText.classList.add('clickable');
    saveText.textContent = 'Add To Favourites';

    // Append
    cardBody.append(saveText);
    link.appendChild(image);
    card.append(link, cardBody);
    imagesContainer.appendChild(card);
  });
}

//  Get 10 Images from Unsplash API
async function getUnplashPictures() {
  try {
    const response = await fetch(apiUrl);
    resultsArray = await response.json();
    console.log(resultsArray);
    updateDOM();
  } catch (error) {
    // Catch Error Here
  }
}

// On Load
getUnplashPictures();

Test React Component in Jest/Enzyme

I am new at react testing, written below code and having few issues, could someone please help me to resolve below issue?

my question is

1.why the test named should call onChange method on input is failing, and any other solution for it?
2. As per report fetch, then and catch method is untested, any way to test it.

my App.js file is like below.

import React, { useState, useEffect } from "react";
import "./App.css";

export default function App() {
  const [data, setdata] = useState([]);
  const [searchId, setSearchId] = useState("");

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/posts?userId=${searchId}`)
      .then((Response) => Response.json())
      .then((data) => setdata(data))
      .catch((err) => {return err})
  }, [searchId]);

  const defaultArticle = [{ userId: 'none', title: 'none', body: 'none'}]

  if(data.length === 0){
    setdata(defaultArticle)
  }

  const handleCange = (e) => {
    setSearchId(e.target.value);
  };

  return (
    <div className="App">
      <h1>Article List</h1>
      <div className="searchBox">
        <input
          type="text"
          placeholder="Enter user ID"
          onChange={(e) => handleCange(e)}
        />
      </div>
      <div className="itemsSec">
        {data.map((articles, index) => (
          <div key={index} className="items">
            <h4>
              <span style={{ fontWeight: "bold" }}>ID:</span> {articles.userId}
            </h4>
            <p>
              <span style={{ fontWeight: "bold" }}>Title: </span>
              {articles.title}.
            </p>
            <p>
              <span style={{ fontWeight: "bold" }}>Content: </span>
              {articles.body ? articles.body : 'null'}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
}

I have written test cases as below.

import React from 'react';
import { render, cleanup } from '@testing-library/react';
import Enzyme from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import { shallow, mount } from 'enzyme';
import App from './App';
import toJson from 'enzyme-to-json';

Enzyme.configure({ adapter: new Adapter() });

afterEach(cleanup)

describe('TextField component', () => {

it('render without crash', () => {
  render(<App />);
});

it("renders correctly", () => {
  const tree = shallow(<App />);
  expect(toJson(tree)).toMatchSnapshot();
});

 it("renders header", () => {
  const wrapper = shallow(<App />);
  const heading = <h1>Article List</h1>;
  expect(wrapper.contains(heading)).toEqual(true);
});

it.skip("contains ID", () => {
  const wrapper = mount(<App />);
  const value = wrapper.find("h4").text();
  expect(value).toEqual("ID: none");
});

it('should call onChange method on input', () => {
  const onChange = jest.fn();
  const event = {
    target: { value: 1 }
  };
  const component = shallow(<App />);
  component.find('input').simulate('change', event);
  expect(onChange).toHaveBeenCalled();
});

});

my terminal test output is like below

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   81.25 |       75 |    62.5 |   81.25 | 
 App.js   |      80 |       75 |    62.5 |      80 | 10-12
 fake.js  |       0 |        0 |       0 |       0 | 
 index.js |     100 |      100 |     100 |     100 | 
----------|---------|----------|---------|---------|-------------------

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 1 skipped, 4 passed, 6 total
Snapshots:   1 passed, 1 total
Time:        3.35 s
Ran all test suites.

my question is

  1. why the test named should call onChange method on input is failing, and any other solution for it?
  2. As per report fetch, then and catch method is untested, any way to test it.

How do I fix this error I am reciving in my weather api, 404? [duplicate]

I have this code that uses thezipcodes.net to get latitude and longitude and then it puts it through api.weather.gov to get the weather. The problem is that it is screwing up in the area where it gets the points in the weather.gov API.

In getweatherforecaststuff() it returns a 404 error and is trying to set the ending to 0,0.

let lat = 0;
let long = 0;
let forecaststring = "";

function getLat(zipcode) {
  //add code here to get from api
  $.getJSON("https://thezipcodes.com/api/v1/search?zipCode=" + zipcode + "&countryCode=US&apiKey=01f2f327b789845bddf7d617257d8f76", function(data) {
    lat = data["location"][0]["latitude"];
    long = data["location"][0]["longitude"];
  });
}

function getWeatherForecastStuff() {
  $.getJSON("https://api.weather.gov/points/" + lat + "," + long + "", function(data) {
    forecaststring = data["properties"]["forecast"];
  });
}

function printStuff(forecaststrings) {
  $.getJSON(forecaststrings, function(data) {
    console.log(data);
  });
}

function getInfoNeeded() {
  zipcode = window.prompt("What is your zipcode?");
  getLat(parseInt(zipcode));
  getWeatherForecastStuff()
  printStuff(forecaststring)
}

Form validation using only JavaScript

I’m currently working on a simple form and I can’t for the life of me get the validation for the radio buttons and checkboxes right! I want to validate if the user chose at least 1 radio button and 1 to 2 checkboxes and if not, show a message next to the label. Afterwards I want to send all these information to an HTML page (for this task should I use POST? I’ve seen people use GET and I’m confused)

Here is how I validated the username

HTML:

<form autocomplete="on" id="form" method="POST">

  <label for="username">Name:<span aria-hidden="true">*</span></label><br>
  <input type="text" id="username" aria-describedby="usernameError" required placeholder="John Smith">
  <div id="usernameError" class="error"></div><br>



  <label for="age">Age:</label>
  <div id="ageError" class="error"></div><br>
  <input type="radio" name="age" id="18-35" value="18-35" aria-describedby="ageError" required>18-35<br>
  <input type="radio" name="age" id="35-50" value="35-50" aria-describedby="ageError" required>35-50<br>
  <input type="radio" name="age" id="50" value="50<" aria-describedby="ageError" required>50 and above<br><br>



  <label for="cars" id="cars_checkboxes">Cars available to test drive:</label>
  <div id="carsRequirements" class="requirements">You must choose at least 1 car and at most 3 cars</div>
  <div id="carsError" class="error"></div><br>
  <input type="checkbox" name="carBrands" id="Toyota" value="Toyota" aria-describedby="carsError" required>Toyota
  <input type="checkbox" name="carBrands" id="Jeep" value="Jeep" aria-describedby="carsError" required>Jeep<br>
  <input type="checkbox" name="carBrands" id="Honda" value="Honda" aria-describedby="carsError" required>Honda
  <input type="checkbox" name="carBrands" id="Ford" value="Ford" aria-describedby="carsError" required>Ford<br>
  <input type="checkbox" name="carBrands" id="Lexus" value="Lexus" aria-describedby="carsError" required>Lexus<br><br><br>



  <input type="reset" value="Reset">
  <input type="submit" value="Submit" class="submit-btn">
</form>

JavaScript:

const form = document.getElementById("form");
form.setAttribute("novalidate", "");
form.addEventListener("submit", (event) => {
  const allInputsValid = event.target.checkValidity();
  if (!allInputsValid) {
    event.preventDefault();
  }
});


const messages = {
  username: {
    valueMissing: "Please enter a name.",
  },
};


function handleInvalidInput(event) {
  const input = event.target;
  input.setAttribute("aria-invalid", true);
  const validity = input.validity;
  const inputMessages = messages[input.id];
  let message = "";
  if (validity.valueMissing) {
    message = inputMessages.valueMissing;
  }
  if (input.type === "text") {
    input.style.border = "solid red 2px";
  }
  const errorId = input.id + "Error";
  const errorContainer = form.querySelector("#" + errorId);
  errorContainer.textContent = message;
}


function clearValidity(event) {
  const input = event.target;
  input.setAttribute("aria-invalid", "false");
  if (input.type === "text") {
    input.style.border = "";
  }
  const errorId = input.id + "Error";
  const errorContainer = form.querySelector("#" + errorId);
  errorContainer.textContent = "";
}

I know how to validate that in the sense that I would go about it like this:

For the checkboxes:

num_of_cars = document.querySelectorAll('input[name="carBrands"]:checked').length;

if (num_of_cars < 1 || num_of_cars > 2) {

return true;

} else {

return false;

}

And for the age:

const age = document.getElementById("age");

if (!age.checked) {

return true;

} else {

return false;

}

But whenever I put them in a function and try to call them inside the event listener of submit everything just stops working even the username validation