Just testing UI stack

I’m writing an async test in Jest for a function that fetches user data:

// userService.js
export async function getUser(id) {
  const response = await fetch(`/api/users/${id}`);
  return response.json();
}

// userService.test.js
import { getUser } from './userService';

test('getUser returns correct user name', () => {
  getUser(1).then(user => {
    expect(user.name).toBe('Alice');
  });
});

When I run this, I see:

 PASS  userService.test.js
  ✓ getUser returns correct user name (5 ms)

However, even if I change the expected name to something else (e.g. ‘Bob’), the test still passes. I expected it to fail when the assertion doesn’t match.

Why is the Query Builder in NestJS (TypeORM/Prisma) faster than Laravel 8 Query Builder?

I’m currently working on backend development using both Laravel 8 (with Eloquent and its query builder) and NestJS (with either TypeORM or Prisma). I’ve noticed that database queries in NestJS seem to execute significantly faster than in Laravel 8, even when performing similar operations and on the same database.

Here are some details:

Both applications are querying the same database on the same server.

Laravel uses Eloquent or the query builder.

NestJS uses TypeORM or Prisma (I’ve tried both).

No significant logic overhead in either framework.

My question is:
What factors might explain the performance difference between the NestJS query builder and Laravel’s query builder? Is it due to how each framework handles database connections, query compilation, or some other internal mechanism?

I’m not trying to start a framework war—just genuinely curious about the technical reasons behind the speed difference.

Thanks in advance!

Why is it easy to check .closed on manual RxJS subscriptions, but not with takeUntilDestroyed() in Angular?

I am using RxJS for subscriptions in Angular. I noticed that when I manually subscribe to an observable and store the Subscription, I can easily check if it was unsubscribed using .closed, especially in ngOnDestroy().

But when I use the newer takeUntilDestroyed() utility (from @angular/core/rxjs-interop), I don’t get a Subscription object, so I can’t check if the unsubscription actually happened. This makes it harder to confirm at runtime whether the observable was cleaned up properly.
Here’s current example of Old Subscription approach:

Manual Subscription (with .closed check):

import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';
@Component({
  selector: 'app-manual-sub',
  template: `<p>Manual subscription</p>`
})
export class ManualSubComponent implements OnInit, OnDestroy {
  subscription!: Subscription;
ngOnInit(): void {
    this.subscription = interval(1000).subscribe(val => {
      console.log('Manual:', val);
    });
  }
ngOnDestroy(): void {
    this.subscription.unsubscribe();
    console.log('Unsubscribed?', this.subscription.closed); // Easy to check
  }
}

My Question:

Is there a way to confirm at runtime that takeUntilDestroyed() actually unsubscribed — similar to how we can check .closed on a Subscription?
Is there a recommended pattern or function to track this more explicitly when using takeUntilDestroyed() ?

Thanks in advance 🙂

Cannot get Chrome extension context menu to work

I’m trying to make a Chrome extension from selecting a text (eventually, I want to be able to add vocab into a separate website).

Obviously, I have to use the context menu API. But I can’t get it to work. Somehow clicking the context doesn’t make anything happen, not even a console.log.

This is my code:

manifest.json

{
  "name": "Hello Extensions",
  "description": "Base Level Extension",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": ["contextMenus"],
  "background": {
    "service_worker": "service-worker.js"
  } 
}

service-worker.js

chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: "meaning",
    title: "meaning",
    contexts: ["selection"]
  });  
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
  console.log(info);
  console.log(tab);
});

Clicking my context menu (which does show up) won’t log anything to the console! I’ve done everything I can, but can’t get it work for the bane of my life.

Would appreciate some help. Thanks!!

Cannot retrieve value of selected radio button

I used Bootstrap to create the radio buttons:

<div id="heightForm">
  <legend class="h">
    Height:
    <div class="form-check form-check-inline weightChoose commonRadio">
      <div class="form-check form-check-inline kg">
        <input class="form-check-input" type="radio" name="heightButtonS" role="radio" value="METER" id="h1"/>
        <label class="form-check-label lbl" for="h1">Meter</label>
      </div>
      <div class="form-check form-check-inline pound">
        <input class="form-check-input" type="radio" name="heightButtonS" role="radio" value="FEET" id="h2"/>
        <label class="form-check-label lbl" for="h2">Feet</label>
      </div>
    </div>
  </legend>
</div>

i wanted to console.log(heightIn);

where

var heightIn = $('input[name="heightButtonS"]:checked').val();

but it gives undefined.

i also tried:

var heightIn = $('input[name=heightButtonS]:checked').val();
var heightIn = $('input[name="heightButtonS"]:checked').value();

This does return the value when there is an attribute “checked” in one of the buttons. Even on selecting the other button it returns the value of that assigned button. I want it to retrieve value for the button which is selected.

Does this not work anymore?

a problem in regard of using api with html and javascript [closed]

I was given a project to build a site that is used for car renting. I am using frontend: html, css and js, and I am stuck.

I was given this API and I have no idea how to get the attributes, data from this API and use them in HTML. I will use an example:

This is the url to the API:
https://rentcar.stepprojects.ge/swagger/index.html

From this URL there is one GET for popular cars.
In my html I made a horizontal scrolling div for these popular cars amongst the users. I have created a single (empty) <div> in this horizontal scroll, which I want to be used as a template, and every time a new div is added, it just adds the data from the API to the template. Additionally I want to add as many divs as there are popular cars in the API response. (Even though I know that is 4 in this case, let’s consider that I do not know it.)

This is the code for horizontal scroll I have created:

ain {
  section {
    display: flex;
    margin: 2%;
  }

  .advertisment {
    justify-content: center;

    .ad {
      width: 40em;
      height: 30em;
      background-color: black;
      margin: 50px;
    }
  }

  .cars {
    flex-direction: column;
    align-items: center;

    .horizontalCars {
      flex-wrap: nowrap;
      overflow-x: auto;
      width: 90vw;
      white-space: nowrap;
      background-color: #333;

      .experimental {
        display: inline-block;
        min-width: 20vw;
        height: 20vw;
        background-color: red;
        margin: 10px;
        color: white;
        text-align: center;
        text-decoration: none;
      }

      div.scrollmenu a:hover {
        background-color: #777;
      }
    }

    .tableCars {
      width: 90vw;
      flex-wrap: wrap;
      justify-content: center;

      .experimental {
        min-width: 20vw;
        height: 20vw;
        background-color: red;
        margin: 10px;
      }
    }
  }
}
<section id="favouriteCars" class="horizontalCars">
  <div id="container" class="experimental"></div>
</section>

Thanks a lot in advance!

How to filter user input in Angular?

I want to filter user input when they type in an HTML text input.

I can do that in native HTML/JavaScript as shown in the following demo:

<form>
    <label for="tracking">Tracking Number:</label>
    <input
        type="text"
        id="tracking"
        name="tracking"
        pattern="^[A-Z]{2}d{9}[A-Z]{2}$"
        title="Format must be like AB123456789CD"
        required
        minlength="13"
        maxlength="13"
    />
</form>

<script>
    const input = document.getElementById('tracking');

    input.addEventListener('input', () => {
        console.log('input fired');

        // Remove non-alphanumeric chars and force uppercase
        input.value = input.value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
    });
</script>

filtering user input with HTML/JS

In the image above, I’m typing a, b, +, – (filtering works like I want).
StackBlitz demo: Filter user input (native)

Now, I’ve done the same thing using Angular (with a template-driven form) as shown in the following demo:

@Component({
  selector: 'app-root',
  template: `
    <form>
      <label for="tracking">Tracking Number:</label>
      <input
        type="text"
        id="tracking"
        name="tracking"
        pattern="^[A-Z]{2}d{9}[A-Z]{2}$"
        title="Format must be like AB123456789CD"
        required
        minlength="13"
        maxlength="13"
        [ngModel]="trackingNumber"
        (ngModelChange)="onTrackingChange($event)"
      />
    </form>
  `,
  imports: [FormsModule],
})
export class App {
  trackingNumber = '';

  onTrackingChange(value: string) {
    console.log('input fired');

    // Remove non-alphanumeric characters and force uppercase
    this.trackingNumber = value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase();
  }
}

filtering user input with Angular

In the image above, I’m typing a, b, +, – (filtering does NOT work like I want). StackBlitz demo: Filter user input (Angular)

As far as my Angular knowledge goes, this happens when the current ngModel value is the same as the new/filtered value, thus Angular does not trigger a change on the HTML text input.

How can I overcome this behavior in Angular?

Can I force Angular to trigger a change?

Is there a way to convert an input value to bold in HTML?

I have the below input value which returns an email address which I’m displaying in a pop up submission box, is there a way to make the input value, ${emailInput.value}, appear bold on my webpage?

function showPopUp() {
  submitBox.classList.toggle("show");
  let successMessage = `A confirmation email has been sent to ${emailInput.value}. Please open it and click the button inside to confirm your subscription`;
  document.querySelector(".confirmation-text").innerText = successMessage;
}

I have tried to use the .bold() method but that isn’t working for me – I’ve read it’s been discontinued for use?

React hook form field resets after submission

The component uses react-hook-form for a two-step form (email then password). After submitting the email address in the first step, the email value appears to be reset to undefined. This prevents the submission of the final form since the email is no longer available.

export default function App() {
  const [inProgress, setInProgress] = useState(false);
  const handleSubmit = (email: string, password: string) => {
    console.log("SimplifiedSignInForTesting submitted:", { email, password });
    setInProgress(true);
    setTimeout(() => {
      setInProgress(false);
    }, 1500);
  };

  return <SignIn submit={handleSubmit} inProgress={inProgress} />;
}

interface SignInProps {
  submit: (email: string, password: string) => void;
  inProgress: boolean;
}

export const SignIn = ({ submit, inProgress }: SignInProps) => {
  const [isEmailSubmitted, setIsEmailSubmitted] = useState(false);

  const schema = z.object({
    email: z.string(),
    password: z.string(),
  });

  type SignInFormData = z.infer<typeof schema>;

  const {
    register,
    handleSubmit,
    setFocus,
    watch,
    formState: { errors, isSubmitting },
  } = useForm<SignInFormData>({
    resolver: zodResolver(schema),
    shouldUnregister: false,
    defaultValues: {
      email: "",
      password: "",
    },
  });

  const onSubmitInternal = useCallback(
    async (data: SignInFormData) => {
      const { email, password } = data;
      console.log(email, password);

      if (!isEmailSubmitted) {
        setIsEmailSubmitted(true);
        setTimeout(() => setFocus("password"), 0);
        return;
      }

      submit(email, password);
    },
    [isEmailSubmitted, setIsEmailSubmitted, submit, setFocus]
  );

  const isLoading = inProgress || isSubmitting;
  const emailErrorMessage = errors.email?.message;

  const email = watch("email");

  React.useEffect(() => {
    console.log(email);
  }, [email]);

  return (
    <form onSubmit={handleSubmit(onSubmitInternal)} noValidate>
      <input
        tabIndex={0}
        autoFocus
        aria-label="email"
        type="email"
        disabled={isLoading || isEmailSubmitted}
        {...register("email")}
      />
      {emailErrorMessage && <span>{emailErrorMessage}</span>}
      <input
        aria-label="password"
        type="password"
        autoComplete="current-password"
        style={{ display: isEmailSubmitted ? "initial" : "none" }}
        disabled={isLoading}
        tabIndex={isEmailSubmitted ? 0 : -1}
        {...register("password")}
      />
      <input
        tabIndex={0}
        type="submit"
        aria-label={isEmailSubmitted ? "login" : "continue"}
      />
    </form>
  );
};

https://codesandbox.io/p/sandbox/affectionate-tu-6fk26l

The form submission should have both the email and password

Can an attacker steal JavaScript local variables via XSS, CSRF, or other attacks?

There is a web page which does not use any cookies:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <script>
    async function handleSubmit(event) {
      event.preventDefault();
      const username = document.getElementById('username').value.trim();
      const password = document.getElementById('password').value.trim();
      document.getElementById('username').value = "";
      document.getElementById('password').value = "";

      const response = await fetch('/path', {
        method: 'GET',
        headers: {
          'Authorization': 'Basic ' + btoa(username + ':' + password)
        },
      });

      const message = await response.text();
      document.getElementById('response_message').innerText = message;

      if (response.ok) {
        document.getElementById('do_something').onclick = async () => {
          const response = await fetch('/another_path', {
            method: 'GET',
            headers: {
              'Authorization': 'Basic ' + btoa(username + ':' + password)
            },
          });
        }
      }

    }
  </script>
</head>

<body>
  <form id="signinForm" onsubmit="handleSubmit(event)">
    <label for="username">Username:</label><br>
    <input type="text" id="username" required><br><br>

    <label for="password">Password:</label><br>
    <input type="password" id="password" required><br><br>

    <button type="submit" id="submit_btn">Submit</button>
  </form>

  <div id="response_message"></div>
  <button id="do_something">Do something</button>
</body>

</html>

After users input their password and get response, the web page shows the response and then allow users do some other things. The response may contain content from attackers. However, for the convenience of users, the script uses the password stored before in a local variable.

Is it possible for attackers to steal the password?

iterate on a json object with for and modfiy the object iterated [duplicate]

I have a json object that I retrieve from an API. Then for each element of this object I need to call another API so that I can retrieve other information I need. So far so good I was able to loop the object and to retrieve the info storing them in a different Json object. My issue now is on updating the object I am iterating:

for (const element of tasks.Tasks.TaskItem) {
    const requestTask = new GetTaskRequest();
    requestTask.name = fileName;
    requestTask.folder = optionalRemoteFolder;
    requestTask.taskUid = element.Uid;
    const result = await tasksApi.getTask(requestTask);
    let task = JSON.parse(result.response.text);
    element.predecessors = task.Task.Predecessors;
    element.successors = task.Task.SubtasksUids;
    taskDetails.push(task);
}

These two lines:

    element.predecessors = task.Task.Predecessors;
    element.successors = task.Task.SubtasksUids;

are my pseudocode for what I want. element is a const so I cannot update it and furthermore the element is a different object from the object I want to update