Mocking function from tested file is not working

I am trying to mock a function from a file which I try to test with Vitest.

test.ts:

export const bar = () => 'bar'
  
export const foo = () => `I am foo. bar is ${bar()}`

test.unit.spec.ts:

import { describe, expect, it, vi } from 'vitest'
import * as testFile from './test'

describe( 'module', () => {
  it( 'foo', () => {
    vi.spyOn(testFile, 'bar').mockImplementation(()  => 'fake bar')
    expect(testFile.foo()).toEqual('I am foo. bar is fake bar')
  })
})

When running the test, I get the following error:

AssertionError: expected 'I am foo. bar is bar' to deeply equal 'I am foo. bar is fake bar'
Expected: I am foo. bar is fake bar
Actual: I am foo. bar is bar

But whenever I put the variable bar into another file, it works fine.

Problems with inherited method in JS

I have problem with an inherited method.
I created a class like this:

class Person {
  #firstName;
  #lastName;
  #birthYear;
  #age;
  #id;

  static #registry = new Registry("personregistry");
  static readRegistryList() {
    return this.#registry.readList();
  }

  constructor(firstName, lastName, birthYear) {
    this.#firstName = firstName;
    this.#lastName = lastName;
    this.#birthYear = birthYear;
    this.#age = this.calculateAge();
    Person.#registry.addToList(this);
    this.#id = this.numberInList();
  }

  numberInList() {
    return Person.#registry.readList().indexOf(this);
  }

  calculateAge() {
    let thisYear = new Date().getFullYear();
    return thisYear - this.#birthYear;
  }

  introduceSelf() {
    return `Hello! I'm ${this.fullName} and I'm ${this.#age} years old.`;
  }
}

And after that a subclass like this:

class Student extends Person {
  #firstName;
  #lastName;
  #birthYear;
  #age;

  constructor(firstName, lastName, birthYear) {
    //super(firstName, lastName, birthYear); --- does not work with private properties
    super();                                  // have to call it empty?
    this.#firstName = firstName;
    this.#lastName = lastName;
    this.#birthYear = birthYear;
    this.#age = this.calculateAge();
}
  calculateAge() {
    let thisYear = new Date().getFullYear();
    return thisYear - this.#birthYear;
  }
  get fullName() {
    return `${this.#firstName} ${this.#lastName}`;
  }
  introduceSelf() {
    return `Hello! I'm ${this.fullName}, a student and I'm ${this.#age} years old.`;
  }
}

If I create an instance of Student the calculateAge() method throws a TypeError because it tries to reach the superclass’s #birthYear.

Very interesting, because if I call introduceSelf() on the same instance it works like a charm. It works even if I do not declare it in the subclass, so inheritance works there fine.

calculateAge() should not work without declaring in the subclass, it should throw the TypeError it does anyway. But why if it is declared in the subclass? ‘this’ should point to the instance, right?

If I rename it like ageCalc() and do not touch the statements at all (and rename it where I call it, in the constructor) it works just fine.

I just don’t get it. An explanation what goes South under the hood would be very much appreciated!

will image lazy loading bypass windows.onload event in certain cases?

I am loading a large number of images on my webpage. My understanding is the using lazy loading allows the windows.onload event to occur sooner. If that’s true, my question is this.. I am using a script section on the page which listens for the windows.onload event. If there are images which are not initially loaded due to lazy loading, will the script miss them or will the windows.onload event fire each time the user scolls and more images load? Here’s the script in question…

  **<script>
    window.onload = function () {
      let elements = document.getElementsByClassName("cat");

      for (let i = 0; i < elements.length; i++) {
        elements[i].style = "cursor: pointer";
        elements[i].onclick = function () {
          saveProfile(elements[i]);
        };
      }
    };
  </script>**

Notification system for blog app in analogy with facebook etc

I tends to extend my blog with notification as used by Facebook and other social media platforms.

Can anyone suggest a notification system for my blog application? I’ve developed a blog with like, comment, and reply features using Django, and now I want to add a notification system. Is there a lightweight notification system available that I can easily implement in my blog app?

Modify source data rxjs

I have observable and I want to modify source (of({lastId, lastCreatedAt}) part) after each iteration of iterateAsync, but return data from listRequest, is it possible?

export const fromListIterator = <T = unknown>(
  listRequest: IteratorFunction<T>,
  limit?: number,
): Observable<T> => {
  return of({ lastId: '', lastCreatedAt: 0 }).pipe(
    mergeMap((source) => [
      from(
        new Iterator<T>(
          () =>
            listRequest(
              { sort: ['id', 'created_at'], page: undefined },
              {
                filter: [
                  new CursorPaginationFilterStrategy(
                    source.lastId,
                    source.lastCreatedAt,
                  ),
                ],
              },
            ),
          limit,
        ).iterateAsync(),
      ).pipe(mergeMap((r) => lastValueFrom(of(r)))),
    ]),
    mergeAll(),
  );
};

Dropdown navigation doesn’t work on mobile devices (JavaScript, HTML, CSS)

I built a navigation using JS and SCSS. On desktop it works totally fine, also some mobile devices like Galaxy S10 show the dropdown menu. But most other mobile devices do nothing when I click the nav elements.

That’s my JS code:

document.writeln(
  ` <ul>
<li><a href="../index.html">Start</a></li>
<li>Menu point 1<i class="fa fa-caret-down" aria-hidden="true"></i><i class="fa fa-caret-right" aria-hidden="true"></i>  
  <ul class="dropdown">
    <li><a href="#">1</a></li>
    <li><a href="#">2</a></li>
    <li><a href="#">3</a></li>
  </ul>
</li>
<li>Menu point 2<i class="fa fa-caret-down" aria-hidden="true"></i><i class="fa fa-caret-right" aria-hidden="true"></i>
    <ul class="dropdown">
      <li><a href="#">1</a></li>
      <li><a href="#">2</a></li>
      <li><a href="#">3</a></li>
    </ul>
  </li>
</ul>`
);

CSS:

nav {
    z-index: 10;
    font-weight: bold;
    text-transform: uppercase;
    color: $color-dark;
    text-decoration: none;

    a {
      &:hover {
        color: $color-accent-dark;
      }
    }

      
      ul {
        list-style: none;
        margin: 0;
        padding-left: 0;

      }
      
      li {
        display: block;
        float: left;
        padding: 1rem;
        position: relative;
        text-decoration: none;
        transition-duration: 0.5s;
        min-width: 90px;

        .fa-caret-right {
          display: none;
        }
      }

        
      li:hover,
      li:focus-within {
        cursor: pointer;
        color: $color-accent-dark;


        .fa-caret-down {
          display: none;
        }

        .fa-caret-right {
          display: inline;
        }

      }
      
      li:focus-within a {
        outline: none;
      }

      ul li:last-child {
        border-bottom-left-radius: 15px;
        border-bottom-right-radius: 15px;
      }
      
      ul li ul {
        visibility: hidden;
        opacity: 0;
        min-width: 5rem;
        position: absolute;
        transition: all 0.5s ease;
        margin-top: 1rem;
        left: 0;
        display: none;
      }
      
      ul li:hover > ul,
      ul li:focus-within > ul,
      ul li ul:hover,
      ul li ul:focus {
         visibility: visible;
         opacity: 1;
         display: block;
         z-index: 15;
      }
      
      ul li ul li {
        background-color: $color-light;
        clear: both;
        width: 100%;
      }

}

I expected it to be clickable on mobile devices too but I can’t find a solution on that. Do you have any ideas? Do I miss something here?

React useState Not Resetting State After Switching Event Handlers

I am trying to reset my form when a user clicks the submit button. The problem I am currently having is that the setFunction for my useState is not updating the form values on form submission. Below is the code.

const [formData, setFormData] = useState({
    date: "", totalincome: "", sidehustleincome: "", stockincome: "", other: ""
})
    
    const handleChange = (event) => {
        const {name, value} = event.target;
        setFormData({
            ...formData,
            [name]: value
        });
    };

    const handleClick = async (event) => {
        event.preventDefault()
        try {
              await fetch(`${import.meta.env.VITE_API_URL}/data/income`, {
                method: "POST",
                body: JSON.stringify(formData),
                headers: {
                    "Content-Type": "application/json",
                  }
              });
              **setFormData({
                date: "", totalincome: "", sidehustleincome: "", stockincome: "", other: ""
            }); ** 
        } catch (err) {
            console.log("An Error has ocurred", err);
        }
        
        
    }

    return (
        <div>
            <p>Add Income</p>
            <form className="box">
                <div className="field">
                <label className="label" for="date">Date:</label>
                <div className="control">
                <input className="input" type="date" id="date" name="date" value={formData.date} onChange={handleChange}/>
                </div>
                </div>
                <div className="field">
                <label className="label" for="totalincome">Total Income:</label><br />
                <div className="control">
                <input className="input" type="text" id="totalincome" name="totalincome" value={formData.totalincome} onChange={handleChange}/><br />
                </div>
                </div>
                <div className="field">
                <label className="label" for="sidehustleincome">Side Hustle Income:</label><br />
                <div className="control">
                <input className="input" type="text" id="sidehustleincome" name="sidehustleincome" value={formData.sidehustleincome} onChange={handleChange}></input><br />
                </div>
                </div>
                <div className="field">
                <label className="label" for="stockincome">Stock Income:</label><br />
                <div className="control">
                <input className="input" type="text" id="stockincome" name="stockincome" value={formData.stockincome} onChange={handleChange}></input><br />
                </div>
                </div>
                <div className="field">
                <label className="label" for="other">Other:</label><br />
                <div className="control">
                <input className="input" type="text" id="other" name="other" value={formData.other} onChange={handleChange}></input ><br />
                </div>
                </div>
                <input className="button is-primary" type="submit" **onClick**={handleClick}/>
                </form>
        </div>
    )
}

My desired functionality is for the page not to reset when the form is sent. I have tried running this code with syntax that should work, and it behaves like there is not a setFunction being called.

const handleClick = async (event) => {
        **event.preventDefault()**
        try {
              await fetch(`${import.meta.env.VITE_API_URL}/data/income`, {
                method: "POST",
                body: JSON.stringify(formData),
                headers: {
                    "Content-Type": "application/json",
                  }
              });
              **setFormData({
                date: "", totalincome: "", sidehustleincome: "", stockincome: "", other: ""
            }); ** 
        } catch (err) {
            console.log("An Error has ocurred", err);
        }
    }

I’ve noticed that the only way to get my code to work properly is to temporarily change the event handler from onClick to onSubmit, save the file, test the functionality, and then switch the event handler back to onClick, saving the file once again.

What is causing this change in functionality? Additionally, why isn’t useState being reset correctly after it’s called before switching the event handler between onClick and onSubmit and saving the file?

Unable to Submit Job Application via Fetch API in Node.js/MongoDB Project

I’m building a Node.js application with MongoDB Atlas where users can create jobs and apply for them. I’ve successfully set up job creation and display the available jobs on the job board, but when trying to submit a job application using a fetch request, the application fails with a 404 Not Found error.

Frontend (job-board.html):
I fetch job listings and dynamically generate job entries with an “Apply” button. The button triggers the applyForJob function that sends a POST request to my /apply-job route.

Backend (server.js):
The backend has a route that handles the /apply-job POST request. The route extracts the jobId, finds the job in the MongoDB collection, and inserts a new application into the applications collection.

It should be noted that I am newer developer learning as I go! Please be gentle.

Remove bg image/color from a lottie animation

I m currently working on my Website project and I m facing a problem. I want to integrate JSON animation in my website and I m succeeded however I dont know how to remove bg color from the lottie animation. Also, I don’t have prior knowledge of JSON neither I can edit JSON on my own could anyone of you help me remove the background from the lottie animation

Thanks,

  • Syed Rohaan

I have tried lottiefile website to remove bg but couldn’t able to do it, and I have also tried lottie editor to see into code if I could remove it or not.

No ‘Access-Control-Allow-Origin’ header is present on the requested resource, CORS error in MERN app

I was working on a project to create a simple payments app and during deployment when I tried to log in to the app I got the below error:

signin:1  Access to XMLHttpRequest at 'https://mere-paise-nikal-backend.onrender.com/api/v1/user/signin' from origin 'https://mere-paise-nikal.onrender.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Now I know what a cors error is and I have included app.use(cors()) in my code but still i am facing this issue.
I deployed the app on render.
Initially, it was working fine but then I copied the project directory to a different directory and after that, it stopped working.
I thought there might be some issues with dependencies and i reinstalled cors but still i cannot resolve the issue.
I would be great if someone could just help me out.

Here is my index.js

const express = require("express");
const mainRouter = require("./routes/index.js");
const cors = require("cors");

const app = express();

app.use(cors());

app.use(express.json());

app.use("/api/v1", mainRouter);

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log("Server is running on port 3000");
});

Here is the github link to my project: https://github.com/iOmKumar30/Mere_Paise_Nikal

Can anyone explain me about this endless iteration of for loop? [duplicate]

While studying loops I learned that we have to be careful while giving conditions when we are using while loop because if condition never becomes false then the loop will never end and it will crash the runtime, so I wanted to do the same experiment with for loop.

I wrote down this code given below :


for(let i=1;i=1;i++)
  {
    console.log(i);
  }

And my experiment was successful because the execution of this loop didn’t stop and printed 1 endlessly, however I realized later that after executing the block of code value of ‘i’ should get incremented and must have become 2 due to which the condition ‘i=1’ should have become false and 2nd iteration of the loop should’ve never happened but that wasn’t the case and the loop went on printing 1 endlessly.

Can anybody help me to understand why it happened like that?

Express.js redirecting to incorrect URL when using custom URL scheme

I’m developing a Node.js application using Express.js, and I’m encountering an issue with URL redirection when using a custom URL scheme. Here’s my setup:

I have an environment variable set up like this:

APP_URL=myapp://confirm

And here’s my Express.js route for user verification:

router.get('/api/verify', async (req, res) => {
  try {
    const { token } = req.query;
    if (!token) {
      return res.status(400).json({ message: 'Verification token is required' });
    }

    const result = await verifyUser(token);

    if (result.verified) {
      const redirectUrl = `${process.env.APP_URL}?email=${encodeURIComponent(result.email)}`;
      res.redirect(302, redirectUrl);
    } else {
      res.status(404).json({ message: 'User not found or already verified' });
    }
  } catch (error) {
    console.error('Error verifying user:', error);
    res.status(500).json({ message: error.message });
  }
});

The problem is that when I try to redirect to my custom URL scheme, Express.js is appending the current host and path to the URL. So instead of redirecting to:

myapp://[email protected]

It’s redirecting to:

http://localhost:3000/v1/api/myapp://[email protected]

This results in a “Cannot GET /v1/api/myapp://confirm” error.

How can I modify my Express.js route to correctly redirect to my custom URL scheme without prepending the current host and path?

The deep link url is supposed to launch an android app instead of making an api request that does not exist.

Why does using AND (&&) work vs. OR (||) when looping through a string looking for select characters?

I have a very basic question about logical operators && vs. ||. I should know this and it bugs me I’m having a hard time wrapping my head around this specific use case.

I’m splitting a string and looping through it and trying to exclude specific characters. For the example below they’re spaces or exclamation marks. Why is using || the incorrect option while using && the correct one? In my mind, since it’s a loop going through each individual character it’s looking to see if it’s this OR that. Not this AND that.

&& operator

const updatedSplit = [];

'Hello my name is Joe!'.split('').forEach(char => {
  if (char !== ' ' && char !== '!') {
    updatedSplit.push(char)
  }
})

console.log(updatedSplit) // ['H', 'e', 'l', 'l','o', 'm', 'y', 'n','a', 'm', 'e', 'i', 's', 'J', 'o', 'e']

|| operator

const updatedSplit = [];

'Hello my name is Joe!'.split('').forEach(char => {
  if (char !== ' ' || char !== '!') { // <-- TS error
    updatedSplit.push(char)
  }
})

console.log(updatedSplit)

enter image description here

How to prevent inputs from being invalid from start and input being valid when user inputs something

How to prevent inputs being invalid(because of css rule they’re all red) on load and why even after inputing value they don’t change to :valid.

 <section>
      <form novalidate id="register-form">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"  required/>
        <label for="country">Country:</label>
        <input type="text" id="country" name="country" required/>
        <label for="code">Zip Code:</label>
        <input type="text" id="code" name="code"required />
        <label for="password">Password:</label>
        <input type="password" name="password" id="password" required/>
        <label for="repeat-password">Repeat password:</label>
        <input type="password" name="repeat-password" id="repeat-password" required/>
        <label>
        <button type="submit">Submit</button>
        <span id="error-span"></span>
      </form>
    </section>
const form = document.querySelector("#register-form");
const emailField = document.getElementById("email");
const countryField = document.getElementById("country");
const codeField = document.getElementById("code");
const passwordField = document.getElementById("password");
const repeatPasswordField = document.getElementById("repeat-password");
const errorSpan = document.querySelector("#error-span");

form.addEventListener("submit", (event) => {
  resetError();
  if (!emailField.validity.valid) {
    showError();
    event.preventDefault();
  }
});

function showError() {
  if (emailField.validity.valueMissing) {
    errorSpan.textContent = "Email missing!";
  }
}
function resetError() {
  errorSpan.textContent = "";
}

input:invalid {
  border: 2px dashed red;
}
input:valid {
  border: 2px solid black;
}

I tried changing order of css rules but it didn’t work