How to run different mocha test files one after another or more than 5 files in parallel?

I am trying to make a Test Automation Cases with mocha js, and facing an issue, that when I try to run mocha test files parallel I can run not more than 5 files and if I try to run without a parallel flag, only first file in the Test folder runs.

How can I run Test Files one after another with mocha? Or maybe there is a way how I can do it with Jenkins?

Nginx + node = get style.css, bundle.js Connection Refused

I’m having trouble uploading my static files to my server,
keeps giving “Connection refused” problems
error message

I checked my firewall, but I didn’t find anything that could cause a problem.

my /etc/nginx/sites-enabled/pedroportifol.com.br settings

server {
    listen 80;
    listen [::]:80;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html index.php;

    server_name pedroportifol.com.br;

    location = /favicon.ico { access_log off; log_not_found off; }
  
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /.ht {
        deny all;
    }

    location ~ /. {
        access_log off;
        log_not_found off;
        deny all;
    }

    gzip on;
    gzip_disable "msie6";

    gzip_comp_level 6;
    gzip_min_length 1100;
    gzip_buffers 4 32k;
    gzip_proxied any;
    gzip_types
        text/plain
        text/css
        text/js
        text/xml
        text/javascript
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/rss+xml
        image/svg+xml;

    access_log off;
    #access_log  /var/log/nginx/pedroportifol.com.br-access.log;
    error_log   /var/log/nginx/pedroportifol.com.br-error.log;

    #include /etc/nginx/common/protect.conf;
}

Could someone please help me?

I checked the firewalls and ports, but found nothing

JavaScript Select function Cars-rental

const carSelector = document.querySelectorAll(".cars-select");
const car = document.querySelectorAll(".car");

carSelector.forEach((selected, index) => {
  selected.addEventListener("click", () => {
    car.forEach((car) => {
      car.classList.remove("show");
    });
    car[index].classList.add("show");
  });
});

This is showing all the time first element, doesn’t matter on which select i click.
I think that “index” is == 0; but idk how to change it.

ChartJs datasets and time mismatch on tooltip

Dataset and time mismatch sample

Hi. I have to use chartjs for a small js application.
I have data from some sensors. It plots the data and dates correctly. But it usually shows errors in the tooltip.

I think I can explain the problem well on the image. When we look at the mouse position, it should show data as of January 30 and only show the Outside1 dataset. But it shows data as of December 20. Also, there is no Outside1 data on December 20th.

Actually,when I look at the data at the clicked location with getElementsAtEventForMode();

Time for Outside1 sensor: Tue Jan 30 2024 16:09:00
Time for the others : Wed Dec 20 2023 17:16:26

I get these values.
//One click, same location

Express middleware in a controller that is in a separate file

I have this code that allows me to use express-fileupload middleware for uploading files:

const fileUpload = require('express-fileupload');

app.use(fileUpload({useTempFiles: true}));

app.post('/upload',   (req, res) => {
   const { image } = req.files;
   ...
}

It works, and the image in the upload endpoint is valid (is the image uploaded by the user in <input type="file" name="image" />).

However most of my routes are located in another file:

app.use('/api', routes);

routes.js:

router.get('/save', controller.save);

and in controller.js:

exports.save = (req, res) => {
    let {image} = req.files;
    ...

The image in the save endpoint would be undefined, because middleware is not applied.

However, if I try to apply it:

router.get('/save', fileUpload, controller.save);

the save endpoint is loading infinitely, the debugger never reaching the code inside the save method.

What am I doing wrong, and how do I get the file from inside the controller that’s in another file?

NodeJS: MongoNotConnectedError: Client must be connected before running operations

I am experiencing MongoNotConnectedError: Client must be connected before running operations using Mocha to test in NodeJS. In the output it shows database has been connected successfully while actually ran the program, but still not passing the test.

Here is my test:

`import mongoose from ‘mongoose’;
import { expect } from ‘chai’;
import importTracks from ‘../../scripts/importTracks.js’;
import { Track } from ‘../../models/track.js’;
import connectDB from ‘../../database.js’;

describe(‘importTracks’, () => {
before(async () => {
await connectDB(); // Adjust for test database
});

after(async () => {
await mongoose.disconnect();
});

it(‘should import tracks from an Excel file’, async () => {
const filePath = ‘./Track Import Test.xlsx’; // Adjust path as necessary
await importTracks(filePath);

const tracks = await Track.find({});
expect(tracks.length).to.be.greaterThan(0);

Additional assertions based on expected test data
});

});“`

And here is my code:


import dotenv from "dotenv";
dotenv.config({ path: "../.env" }); // Adjust the path as necessary

import mongoose from "mongoose";
import xlsx from "xlsx";
import connectDB from "../database.js"; // Adjust path as necessary
import { Contract } from "../models/contract.js"; // Adjust path and ensure export style matches
import { Track } from "../models/track.js"; // Adjust path and ensure export style matches

const importTracks = async (filePath) => {
await connectDB();

Ensure "Contract 1" exists
let contract = await Contract.findOne({ name: "Contract 1" });
if (!contract) {
contract = new Contract({ name: "Contract 1" });
await contract.save();
  }

Load and read the Excel file
const workbook = xlsx.readFile(filePath);
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
const data = xlsx.utils.sheet_to_json(sheet);
const errorLog = [];

Process each track
for (const item of data) {
const { Title, Version, Artist, ISRC, PLine, Aliases } = item;
if (!Title || !ISRC) {
if (
ISRC ==
        "Any dashes, spaces or other characters will be stripped out on import"
      ) {
continue;
      }
console.error(
        `Missing required fields for track: ${JSON.stringify(item)}`
      );
errorLog.push(
        `Missing required fields for track: ${JSON.stringify(item)}`
      );
continue;
    }

const aliasesArray = Aliases
Aliases.split(";").map((alias) => alias.trim())
[];

const track = new Track({
title: Title,
version: Version || "",
artist: Artist || "",
isrc: ISRC,
pLine: PLine || "",
aliases: aliasesArray,
contract: contract._id,
    });

try {
await track.save();
console.log(`Track ${Title} imported successfully.`);
catch (error) {
console.error(`Failed to save track: ${Title}. Error: ${error.message}`);
errorLog.push(`Failed to save track: ${Title}. Error: ${error.message}`);
    }
  }

if (errorLog.length > 0) {
console.log("Some errors occurred during import:");
errorLog.forEach((err) => console.log(err));
else {
console.log("All tracks have been imported successfully.");
  }

await mongoose.disconnect();
};

export default importTracks;```

Track.js:
```import mongoose from 'mongoose';

const trackSchema = new mongoose.Schema({
title: { type: String, required: true },
version: String,
artist: String,
isrc: { type: String, required: true },
pLine: String,
aliases: [String],
contract: { type: mongoose.Schema.Types.ObjectId, ref: 'Contract' }
});

Export the Track model as a named export
export const Track = mongoose.model('Track', trackSchema);

Can anyone please help me to troubleshoot where the problem is from?

I am experiencing MongoNotConnectedError: Client must be connected before running operations using Mocha to test in NodeJS.

Firestore .for is not iterable

This code is giving me an error ‘.for is not iterable’:

const colRef = db.collection('tenants').doc(tenantId).collection('supplies')
const items = []
const query = colRef.where('stockGrams', '>', 0) // Get all items with stock left
const querySnapshot = await query.get()
if (!querySnapshot.empty) {
  querySnapshot.forEach(doc => { // Error occurs here!
    items.push(doc.data()) // Add each item to our list
  })
}

Tried something simple:

const querySnapshot = await colRef.limit(5).get()

but still get the same error.

React vs JS event handlers for clicking outside the component, which one is best practice?

I am creating a menu component in React where when the menu opens, and user clicks anywhere outside the menu it’ll close the menu component. There are two approaches I saw, one is to use JS event listener like this

import React, { useState, useEffect } from 'react';

const Dropdown = () => {
  const [isOpen, setIsOpen] = useState(false);
  
  const toggleDropdown = () => setIsOpen(!isOpen);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (isOpen && !event.target.closest('.dropdown')) {
        setIsOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  return (
    <div className="dropdown" onClick={toggleDropdown}>
      {isOpen ? (
        <div className="dropdown-menu">
          {/* Dropdown Content */}
        </div>
      ) : null}
    </div>
  );
};

Another approach would be in with React event handler like this:

import React, { useState } from 'react';

const Dropdown = () => {
  const [isOpen, setIsOpen] = useState(false);

  // Toggle Dropdown open/close
  const toggleDropdown = () => setIsOpen(!isOpen);

  // Close Dropdown if open, when clicking outside
  const handleClickOutside = (e) => {
    if (isOpen && !e.currentTarget.contains(e.target)) {
      setIsOpen(false);
    }
  };

  return (
    <div onClick={handleClickOutside}>
      <button onClick={(e) => {
        e.stopPropagation(); // Prevents click from "bubbling" up to the div
        toggleDropdown();
      }}>
        Toggle Dropdown
      </button>
      {isOpen && (
        <div className="dropdown-menu">
          {/* Dropdown content */}
        </div>
      )}
    </div>
  );
};

so which one is more of a best practice ? on one hand you have to assign global event listeners, on one hand you are dealing with event bubbling in react.

Can’t render two markets at a same time @react-google-maps/api

I am having trouble while rendering multiple markers on the google map through the map function. One marker should render based on ‘source’ state and one should render based on ‘destination’ state. When I’m typing in the source input the marker is rendering on the lats and lngs of source. But when I’m typing in the destination input it is shifting to the lats and lngs of destination.
Here is the map.js:

"use client";
import React, { useContext, useEffect, useState } from "react";
import {
  DirectionsRenderer,
  GoogleMap,
  MarkerF,
  OverlayView,
  OverlayViewF,
  useJsApiLoader,
} from "@react-google-maps/api";
import { SourceContext } from "../../context/SourceContext";
import { DestinationContext } from "../../context/DestinationContext";

function Map() {
  const containerStyle = {
    width: "100%",
    height: window.innerWidth * 0.8,
  };

  const { source, setSource } = useContext(SourceContext);
  const { destination, setDestination } = useContext(DestinationContext);

  const [center, setCenter] = useState({
    lat: -3.745,
    lng: -38.523,
  });
  const [map, setMap] = React.useState(null);
  const [directionRoutePoints, setDirectionRoutePoints] = useState([]);
  useEffect(() => {
    if (source && source.length !== 0 && map) {
      map.panTo({
        lat: source.lat,
        lng: source.lng,
      });
      setCenter({
        lat: source.lat,
        lng: source.lng,
      });
    }
    if (source.length != [] && destination.length != []) {
      console.log("DIE");
      directionRoute();
    }
  }, [source]);

  /**
   * Used when Destination Value Available
   */
  useEffect(() => {
    if (destination?.length != [] && map) {
      setCenter({
        lat: destination.lat,
        lng: destination.lng,
      });
    }

    if (source.length != [] && destination.length != []) {
      console.log("DIE");
      directionRoute();
    }
  }, [destination]);

  /**
   * Used to Get Direction Router Points
   */
  const directionRoute = () => {
    const DirectionsService = new google.maps.DirectionsService();
    console.log("DIE");
    DirectionsService.route(
      {
        origin: { lat: source.lat, lng: source.lng },
        destination: { lat: destination.lat, lng: destination.lng },
        travelMode: google.maps.TravelMode.DRIVING,
      },
      (result, status) => {
        if (status === google.maps.DirectionsStatus.OK) {
          setDirectionRoutePoints(result);
        } else {
          console.error("Error");
        }
      }
    );
  };

  return (
    <GoogleMap
      mapContainerStyle={containerStyle}
      center={center}
      zoom={11}
      onLoad={(map) => setMap(map)}
      options={{ mapId: "4113717585f11867" }}
    >
      {source.length != [] ? (
        <MarkerF
          position={{ lat: source.lat, lng: source.lng }}
          icon={{
            url: "/source.png",
            scaledSize: {
              width: 20,
              height: 20,
            },
          }}
        >
          <OverlayViewF
            position={{ lat: source.lat, lng: source.lng }}
            mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
          >
            <div className="p-2 bg-white font-bold inline-block">
              <p className="text-black text-[18px]">{source.label}</p>
            </div>
          </OverlayViewF>
        </MarkerF>
      ) : null}

      {destination.length != [] ? (
        <MarkerF
          position={{ lat: destination.lat, lng: destination.lng }}
          icon={{
            url: "/dest.png",
            scaledSize: {
              width: 20,
              height: 20,
            },
          }}
        >
          <OverlayViewF
            position={{ lat: destination.lat, lng: destination.lng }}
            mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
          >
            <div className="p-2 bg-white font-bold inline-block">
              <p className="text-black text-[18px]">{destination.label}</p>
            </div>
          </OverlayViewF>
        </MarkerF>
      ) : null}

      {/* <DirectionsRenderer
        directions={directionRoutePoints}
        options={{
          polylineOptions: {
            strokeColor: "#000",
            strokeWeight: 5,
          },
          suppressMarkers: true,
        }}
      /> */}
    </GoogleMap>
  );
}

export default Map;

I’ve tried logging the source and destination states on console, it seems like the source state is being erased when destination is inputted.

Why my chrome.storage.session object is not ever updated?

I need some help to improve my scraper chrome extension.
I try to summarize what the extension does:

  1. clickin’ a button in popup.html it opens 10 tabs
  2. in my background there is the listener chrome.tabs.onUpdated that scrapes data in the tabs (when status == complete) and then updates the storage.session in this way:

code

chrome.storage.session.get(function(cfg) {
        if(typeof(cfg["riassunti"]) !== 'undefined' && cfg["riassunti"] instanceof Array) { 
            cfg["riassunti"].push(riassuntoEvento);
        } else {
            cfg["riassunti"] = [riassuntoEvento];
        }
        chrome.storage.session.set(cfg); 
    }); chrome.runtime.sendMessage({riassuntoEvento, from: "scrapeRiassuntoFromPage"});

finally, clicking another button in popup.html, I access to the chrome.storage.session object to retrieve stored data and create a CSV with simple code:

exportBtn.addEventListener("click", async () => {
if(document.getElementById("linkCSV")){
    document.getElementById("linkCSV").remove();
}

const scrapedData = await chrome.storage.session.get();
//alert(Object.values(scrapedData));
console.log(scrapedData); ...

Everything works fine BUT not ever!. Sometimes I miss some data of some tab and I cannot understand why. Do you have any tips?
Thanks

Autocomplete in Javascript /HTML – find array index of clicked value

Its my first post, so thanks in advance, and I hope I have posted correctly.
I am using the “autocomplete” code at W3Schools

(JS part of the code is below).
On event “click”, I need to find the array index of the clicked result.
In my adapted version I have added a hidden value for the array index under with an “id” of ‘place_Index’.
However, the Event Listener (and !e.target!) return the string result from the Input text box (i.e. not the inner.HTML / hidden values).

JS code below

Even if I find a way to access the ‘place_Index’ value, the result is the index of the first item in the autocomplete-list, not the index for the selected item.
I am still a ‘noob’ so would rather achieve this with Vanilla JS rather than via a Library / plug in.
I genuinely have searched Stackoverflow, and the web, but cant locate an answer that produces the required result. Thanks in advance.

function autocomplete(inp, arr) {
  /*the autocomplete function takes two arguments,
  the text field element and an array of possible autocompleted values:*/
  var currentFocus;
  /*execute a function when someone writes in the text field:*/
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      /*close any already open lists of autocompleted values*/
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      /*create a DIV element that will contain the items (values):*/
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      /*append the DIV element as a child of the autocomplete container:*/
      this.parentNode.appendChild(a);
      /*for each item in the array...*/
      for (i = 0; i < arr.length; i++) {
        /*check if the item starts with the same letters as the text field value:*/
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          /*create a DIV element for each matching element:*/
          b = document.createElement("DIV");
          /*make the matching letters bold:*/
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          /*insert a input field that will hold the current array item's value:*/
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
**          b.innerHTML += "<input type='hidden' name = 'place_Index' id = 'place_Index' value='" + Div_Array_Counter + "'>";**
          /*execute a function when someone clicks on the item value (DIV element):*/
              b.addEventListener("click", function(e) {
              /*insert the value for the autocomplete text field:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              /*close the list of autocompleted values,
              (or any other open lists of autocompleted values:*/
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  /*execute a function presses a key on the keyboard:*/
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        /*If the arrow DOWN key is pressed,
        increase the currentFocus variable:*/
        currentFocus++;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 38) { //up
        /*If the arrow UP key is pressed,
        decrease the currentFocus variable:*/
        currentFocus--;
        /*and and make the current item more visible:*/
        addActive(x);
      } else if (e.keyCode == 13) {
        /*If the ENTER key is pressed, prevent the form from being submitted,*/
        e.preventDefault();
        if (currentFocus > -1) {
          /*and simulate a click on the "active" item:*/
          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {
    /*a function to classify an item as "active":*/
    if (!x) return false;
    /*start by removing the "active" class on all items:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*add class "autocomplete-active":*/
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    /*a function to remove the "active" class from all autocomplete items:*/
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    /*close all autocomplete lists in the document,
    except the one passed as an argument:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
      x[i].parentNode.removeChild(x[i]);
    }
  }
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
    closeAllLists(e.target);
});
}
autocomplete(document.getElementById("myInput"), countries);

OBS web socket disconnecting immediately after starting server

I’m trying to create an app to control OBS but I was testing to establish a connection with node and it disconnects immediately after running the server. I have the correct port and password and it is allowed through my firewall.


const WebSocket = require('ws');

const obsAddress = 'ws://localhost:4455'; 
const obsPassword = 'xxxxxxxxxxxxx';
const obsSocket = new WebSocket(obsAddress);

obsSocket.on('open', function () {
    console.log('Connected to OBS WebSocket');
    
    const authMessage = {
        "request-type": "GetAuthRequired"
    };
    
    obsSocket.send(JSON.stringify(authMessage));

    obsSocket.on('message', function (data) {
        const message = JSON.parse(data);
        if (message['status'] === 'error') {
            console.error('Error:', message['error']);
        } else {
            console.log('Success:', message);
        }
    });
});

obsSocket.on('error', function (error) {
    console.error('WebSocket Error:', error);
});

obsSocket.on('close', function () {
    console.log('Connection to OBS WebSocket closed');
});

And here’s the terminal log after using ‘node obs.js’

Connected to OBS WebSocket
Success: {
  d: {
    authentication: {
      challenge: 'd506cAvkZXWs5kkfrJpm0+DUO1fGEr0JjxwRXQYn16w=',
      salt: 'binILkPgQrBli3KGSM/bRf4spegQQ3XRsMO7jRgJcwc='
    },
    obsWebSocketVersion: '5.3.4',
    rpcVersion: 1
  },
  op: 0
}
Connection to OBS WebSocket closed

I’d like the connection to stay so I’m able to communicate and send requests or messages to OBS Web Socket to be able to build the app.

I heard it suggested that CORS or Cross-Origin Requests might be the issue but I’m not sure how to fix this specifically. Any suggestions appreciated!

My are the right and left cookie disappearing when clicked? I want to animate them but the animation is not working [closed]

https://codepen.io/cory-adams/pen/qBwrWYN I’ve played with chat GPT as im usually able to troubleshoot there but the tips it gave me were not helpful

it suggested to add these to two seperate

setTimout(()=>{} cookie.classList.add('cookie-animate'); cookie.classList.remove('cookie-animate');

to prevent the cookies from disappearing

Select Field to Insert Text & Trigger

Here is the HTML in question:

<span class="textInputWithDebounce relative flex flex-auto" data-testid="textInputWithDebounce"><input type="text" placeholder="Enter a value" class="col-12 px1 py-half truncate" aria-label="Filter comparison value" name="textInputWithDebounce" value="" style="border: 0px;"><i class="noevents flex items-center"></i></span>

I have a field (“Enter a value”) that I’m trying to input text into. I am able to set the field to specific text but I can’t trigger the field so that the value stays.

I have also tried instead to simply ‘click’ or ‘focus’ the field so that I can simply type in the text and then hit enter, but I can’t seem to ‘focus’ the field in question.

These will set the value:

document.querySelector('[placeholder="Enter a value"]').value = "Test Value";
document.querySelector('[aria-label="Filter comparison value"]').value = "Test Value";

I tried these also and the value doesn’t stay:

var el = document.querySelector('[placeholder="Enter a value"]');
el.value = 'Test Value'
el.dispatchEvent(new Event('change'));

var el = document.querySelector('[placeholder="Enter a value"]');
el.value = 'Test Value'
el.dispatchEvent(new Event('input', { 'Test Value': true }));

For just simply focusing the field I have tried this:

These both come back undefined:

document.querySelector('[placeholder="Enter a value"]').focus();
document.querySelector('[aria-label="Filter comparison value"]').focus();

Any help is greatly appreciated!