My feature steps are being highlighted as Undefined, but the methods behind them run fine during execution?

I’m working with Cypress and decided to install Cucumber, ive created a feature file which successfully runs the step definitions in the Cypress runner but my cucumber steps are still being highlighted as Undefined in VS Code

Ive tried lots of different configs for the cypress.config.js file but cant get anything to work

There is a similar post in Stackoverflow but that solution wouldnt work for me as i dont use Intellij or TypeScript

Any help appreciated

Here are my dependencies:

    "@badeball/cypress-cucumber-preprocessor": "^21.0.2",
"@cypress/webpack-preprocessor": "^6.0.2",
"@testing-library/cypress": "^10.0.2",
"cypress": "^13.15.0",
"globals": "^15.11.0",
"webpack": "^5.96.1",
"webpack-cli": "^5.1.4",
"@bahmutov/cypress-esbuild-preprocessor": "^2.2.3"

Here is my cypress.config.js file

const createBundler = require("@bahmutov/cypress-esbuild-preprocessor");
const cucumberPreprocessor = require("@badeball/cypress-cucumber-preprocessor");
const esbuildPreprocessor = require("@badeball/cypress-cucumber-preprocessor/esbuild");

module.exports = {
  e2e: {
    specPattern: [
      'cypress/e2e/**/*.feature', // Define path to feature files
      'cypress/e2e/0-test/*.js', // Define path for regular specs
      // 'cypress/e2e/support/step_definitions/**/*.js', // Define the glue path
    ],
    // stepDefinitions: 'cypress/e2e/support/step_definitions/**/*.js', // Explicitly set the path for step definitions
    async setupNodeEvents(on, config) {
      await cucumberPreprocessor.addCucumberPreprocessorPlugin(on, config);
      on(
        "file:preprocessor",
        createBundler({
          plugins: [esbuildPreprocessor.createEsbuildPlugin(config)],
        })
      );
      return config;
    },
  },
};

Here is my feature file

Feature: Example Feature

  Scenario: Example Scenario
    Given I visit the home page
    Then I should see the welcome message

Here are my step definitions

const { Given, Then } = require("@badeball/cypress-cucumber-preprocessor");

Given("I visit the home page", () => {
  debugger;
  cy.visit("https://example.com");
});

Then("I should see the welcome message", () => {
  cy.contains("Example Domain");
});

My folder structure

My folder structure

How does one get the ID from the response body with Mocha test, then use that ID and delete the item?

I am creating a location on the API, the location gets created but then populates an ID, this ID changes all the time. How do I write my Mocha tests to get the ID of the created location, even though the ID changes? Is there a way I can print this ID out?

Below is my test:

   describe("Create a location with all the crud information ", function () {
      it("It should return location crud successfully", async function () {
        request = getCreateLocationsRequest();
        response = await PostCreateLocation({
          token: accessToken,
          requestBody: request,
        });
        expect(response).to.not.be.empty;
        expect(response.status).to.eql(200);
        expect(response.body.locations).to.not.be.empty;
        expect(response.body).to.have.property("locations");
        expect(response.body.location).to.have.property("id");
      });

This is the response if I run it in Postman.

{
    "location": {
        "id": 123,
        "internalId": 123,
        "codeId": null,
        "version": "1.0.0",
        "activeIntel": true,
        "selectable": true,
        "viewable": true, 
        "tfgid": 6,
        "polPrnttId": 123,
        "intPrntId": 123,
        "navPrntId": 123,
        "hgdID": 132,
        "country": "England",
        "lat": -10.33333333,
        "lon": 100.1,
        "kl2": "EN",
        "lka3": "SAA",
        "jklNumeric": "940",
        "notes": "my user notes1",
        "timeZone": "any",
        "lastUpdatedBy": "A Person",
        "lastUpdatedAt": "2024-11-04 11:57:55.212838+00",
        "deletedAt": null
    },}}

How do I assert or expect this ID and display it, so that I can pass it through my deleted tests?

TanStack Table – Sort Favorited and Unfavorited while favorited remains at the top

I have data passed to TanStack Table where they can be either favorited or not. I want to sort the data but the favorited will always be at the start of the table while still being sorted (grouping the data from favorited then unfavorited).

Here’s my custom sort fn

export const customSort: SortingFn<TableData> = (
  rowA: Row<TableData>,
  rowB: Row<TableData>,
  columnId: string,
) => {
  const aIsFavorite = rowA.original.isFavorite;
  const bIsFavorite = rowB.original.isFavorite;

  if (aIsFavorite !== bIsFavorite) {
    return aIsFavorite ? -1 : 1;
  }

  //sort by date if column being sorted is updatedAt
  if (columnId === 'updatedAt') {
    if (rowA.original.updatedAt && rowB.original.updatedAt) {
      const dateA = new Date(rowA.original.updatedAt);
      const dateB = new Date(rowB.original.updatedAt);
      return dateB.getTime() - dateA.getTime();
    }
  }

  //sort alphabetically if column being sorted is name
  if (columnId === 'name') {
    const nameA = rowA.original.name as string;
    const nameB = rowB.original.name as string;
    if (nameA > nameB) return 1;
    if (nameA < nameB) return -1;
    return 0;
  }

  return 0;
};

Then the sort fn is used in the columns that is going to be passed to my TanStack Table

 const columns: ColumnDef<WorkspaceTableData>[] = [
    {
      id: 'name',
      accessorKey: 'name',
      header: "NAME",
      enableSorting: true,
      cell: (info) => info.getValue(),
      sortingFn: customSort,
    },
    {
      id: 'updatedAt',
      accessorKey: 'updatedAt',
      header: "UPDATED AT",
      enableSorting: true,
      size: 140,
      sortingFn: customSort,
    },
  ];

But whenever I try to sort descending, the favorited are now sorted at the bottom. Is there a way to sort the data and always position the favorited to be at the start of the table. Sorting ascending works just fine and the favorites are at the top followed by the unfavorited

Fetch url file, add to input [closed]

So, I have a website that runs a basic HTML page which lists out urls for files in a folder on my site.
I can easily embed these urls into links and make them fully downloadable.

On my page, I want to render the file on screen. I already have code that will do this via an input like this

<input id="files" type="file" accept=".pdf"/>

I then have a standard html button that takes the file contents from the file input and renders the pdf on screen. This works absolutely fine if I use the files input to choose a pdf from my PC.

But, I want to display files from my site, not my computer. I want the user to click whichever file url they want, then have the JS fetch that file, put it into the files input selector and then trigger the rendering function. This should happen automatically.

This is where I’m going wrong. When the user clicks to upload a file from their machine, everything works fine, but I need to offer the user the option of instead clicking a url to one of my files and have that follow the same process

I have had some success in grabbing the file from the url using the fetch API in Javascript. I can fetch it very simply with this code:

fetch('url-of-my-local-file')
            .then(function (file) {
                console.log(file);
            });

And this will fetch the file and show me its done so in the console log. But I have a feeling I am just fetching the promise of a file, not the actual file.

I also don’t know how to then send that file to my files input to get it to render. I think it’s something to do with list.items and data transfer, like this:

let list = new DataTransfer();
list.items.add(response.<response from my file fetch>);

but I just hit JS errors and not being a JS expert I’m getting lost.

EDIT: Thanks to some comments on handling this via a blob, I have now got the code working properly. Thank you.

How to send via Ton Connect UI correctly?

So I am sending the message via sendTransaction



const transaction = {
    validUntil: Math.floor(Date.now() / 1000) + 1360,
    messages: []
};

function addMessage(maddress, amount, payload) {
        transaction.messages.push({
        address: maddress,
        amount: "100000000"
    });
}

I start debugging through the console, everything is correct, it transmits messages and address
As a result, when a notification arrives, it is displayed that I am sending to the address 0.1 TON and receiving 0.09 TON to my own address, I confirm, it takes a commission and sends to my same address from another address.
As a result, I confirm that the coins come from another address to mine, I just took a commission.
I wanted the coins to be sent to the address that I specify, as a result, it simply transfers the coins among themselves.

check address https://tonscan.com/UQANVWNwtjtHqRZuLIs6Svl_zWaj32eIBTlauFaYmXAAPKzm

Getting the font of powerpoint slides using Office JS

I am working on creating a taskPane integration for microsoft powerPoint web and I am trying to get the font of each slide. This is the code I am working with

async function validateSlideDeck() {
await PowerPoint.run(async (context) => {
    const slides = context.presentation.slides;
    slides.load("items");
    await context.sync();

    for (let slide of slides.items) {
        slide.shapes.load("items");
        await context.sync();

        for (let shape of slide.shapes.items) {
            // Check if the shape has a text frame
            if (shape.textFrame) {
                shape.textFrame.textRange.load("text");
                shape.textFrame.textRange.load("font"); // Load font properties to validate
                await context.sync();

                // Ensure there is actual text in the text range
                if (shape.textFrame.textRange.text && shape.textFrame.textRange.text.length > 0) {
                    const font = shape.textFrame.textRange.font;
                    console.log(font.name);
                }
            }
        }

The code is working fine and returning the correct font whenever I am selecting the text and changing the font after it is written. But it is returning empty value whenever I am changing the font via the Home tab and then writing any text.

Is there any way to get the value of a font when it is applied via Home Tab and not selecting the text and changing it after?

Thanks

Typescript infer type of parameter without generic

I am creating a complex table configuration type, where I would like to infer the type of a value based on an accessor key.

The column configuration type looks like

type ColumnConfig<Row,Acc extends keyof Row = keyof row> = {
  accessor: Acc;
  render: React.FC<{value: Reducer<A, Row>}>;
}

The above works absolutely fine when both args are passed:

const foo: ColumnConfig<{foo: 'bar'}, 'bar'> = {
 accessor: 'bar',
 render: ({value}) => <></> // Value type hint is 'bar'
}

However, I don’t always want to pass in the generic arg, as I would like to infer it.

const foo: ColumnConfig<{foo: 'bar'}> = {
 accessor: 'bar',
 render: ({value}) => <></> // Value type hint is keyof {foo: 'bar'}
}

It feels like typescript is refusing to infer the type whenever I pass any of the generic args. Is there a good way to get around this?

I have tried moving things around but I can’t get away without passing the Row type here, else I lose type hinting in the accessor field.

Send events to Google Tag Manager when Google Sign-in button is clicked

I’m working on implementing custom events in Google Tag Manager for my website, and it’s mostly going well — except for one issue. I’m trying to trigger a GTM event when the Google Sign-in button is clicked. Typically, for other buttons on the site, I can simply add an onclick function to initiate the event, but the Google Sign-in button behaves differently.

Since it’s rendered using Google’s API (as shown in the code below), I haven’t been able to attach event listeners or directly manipulate its DOM elements to trigger the GTM event. Does anyone know of a way to set up a GTM event for clicks on Google-rendered buttons like this?

Here is the cshtml that renders the button:

<div class="login-form-group">
    @{
        var clientId = Configuration.GetSection("Authentication:Google:ClientId").Value;
        <script src="https://accounts.google.com/gsi/client" async defer></script>
        <div id="g_id_onload" data-client_id=@clientId data-callback="googleCallbackHandler"
            data-auto_prompt="false" data-ux-mode="redirect" data-use_fedcm_for_prompt="false">
        </div>
        <div class="g_id_signin" data-type="standard" data-size="large" data-theme="filled_blue" 
            data-text="sign_in_with" data-shape="rectangular" data-logo_alignment="left"
            data-locale="en" type="submit">
        </div>
    }
</div>

And here is the javascript code I’ve tried using for triggering the event:

const googleButton = document.getElementsByClassName("login-form-group")[0];
if(googleButton) {
    console.log("googleButton exists")
    googleButton.addEventListener("click", () => {
        console.log("googleButton was clicked")
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            'event': 'googleButtonClick'
        });
        console.log("googleButtonClick event sent");
    })
}

The first console log is executed, but not the second or third. I’ve tried giving the parent div its own ID and using that to attach the event listener, but that didn’t work either. Neither did attaching event listeners to the child elements that are rendered by Google and thus can’t be found in my html.

Is there a way to perform regex route parameter matching in Express 5.0.0 after the removal of regex in strings?

Express 5.0.0 contained a number of breaking changes, including the removal of support for RegExp in strings.

Documentation provides guidance to replace RegExps that were used to construct the route patterns, but I cannot find any documentation on type guarding route parameters like you were able to in Express 4.

Example:

Express 4

I have middleware that sets an ‘application context’ for all requests. It does so if the route follows the pattern /applicationID, where application ID is a UUID.


const applicationContext = Router({ mergeParams: true });

applicationContext.use('/:applicationID([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})',
                       function (req, res, next) {
                           return requireRouteParamsMiddleware([ 'applicationID' ])(req, res, (err) => {
                               if (err) {
                                   return next(err);
                               }
                               return setApplicationContext(req, res, next);
                           });
                       });

Question: How would I be able to achieve the same in Express 5, type guarding the applicationID route parameter to only match upon matching the UUID RegExp pattern?

Thanks for your help in advance!

I tried substituting the string with a new RegExp(...) but quickly realised that (to my knowledge) there was no way to retain the route parameter name in doing so.

Add scroll method but it’s showing error on console onScroll is not defined

Add scroll event and it’s showing in console onScroll is not define

Here is my code

$('.profile - navigation ul li a').on('click', function () {

    var scrollAnchor = $(this).attr('data-scroll'),
        scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top - 28;

    $('body,html').animate({
        scrollTop: scrollPoint
    }, 500);

    return false;

})

$(window).scroll(function () {

    if ($(this).scrollTop() < $('section[data-anchor="top"]').offset().top) {
        $('.profile - navigation ul li a').removeClass('active');
    }

    if ($(this).scrollTop() >= $('section[data-anchor="top"]').offset().top) {
        $('.profile - navigation ul li a').removeClass('active');
        $('.profile - navigation ul li a:eq(0)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="news"]').offset().top) {
        $('.profile - navigation ul li a').removeClass('active');
        $('.profile - navigation ul li a:eq(1)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="products"]').offset().top) {
        $('.profile - navigation ul li a').removeClass('active');
        $('.profile - navigation ul li a:eq(2)').addClass('active');
    }
    if ($(this).scrollTop() >= $('section[data-anchor="contact"]').offset().top) {
        $('.profile - navigation ul li a').removeClass('active');
        $('.profile - navigation ul li a:eq(3)').addClass('active');
    }

});

$(window).scroll(function () {

    if ($(window).scrollTop() >= 100) {

        $('.profile-navigation').addClass('fixed');

    } else {

        $('.profile-navigation').removeClass('fixed');

    }

});

NO overload matches this call in typescript

I’m using typescript to build a micro service in MERN stack but recently i have encountered an error with overload matches that point me to the index.d.ts file which I’m afraid to change

import express from "express";
import MyUserController from "../controllers/MyUserController";

const router = express.Router();

router.post("/", MyUserController.createCurrentUser);

export default router;

it bring a red line at:

router.post("/", MyUserController.createCurrentUser);

but also the code to my routes where inside the try catch block bring the error:

and especially the code: brings the error when i try to comment it out it goes away

if (existingUser) {
            return res.status(200).send();
        } 
try {
        const { auth0Id } = req.body;
        const existingUser = await User.findOne({ auth0Id });

        if (existingUser) {
            return res.status(200).send();
        } 

        const newUser = new User(req.body);
        await newUser.save();

        res.status(201).json(newUser.toObject());
    } catch (error) {
        console.log(error);
        res.status(500).json({ message: "Error creating user" });
    }
};

after trying to run the code it brought an error:

can anyone please help me solve this error:

return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/routes/MyUserRoute.ts:6:18 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request, res: Response) => Promise<Response<any, Record<string, any>> | un
defined>' is not assignable to parameter of type 'Application<Record<string, any>>'.
      Type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<an
y, Record<string, any>>) => Promise<...>' is missing the following properties from type 'Application<R
ecord<string, any>>': init, defaultConfiguration, engine, set, and 63 more.

6 router.post("/", MyUserController.createCurrentUser);
                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  node_modules/@types/express-serve-static-core/index.d.ts:164:5
    164     (path: PathParams, subApplication: Application): T;
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The last overload is declared here.





Resizing iframe from JavaScript results high CLS

I have an iframe on my site that displays a list. At the bottom of the list there is a “See more” button, once the user presses it, the list will expand. The iframed site uses parent.postMessage to notify my site of the height changes:

parent.postMessage({"height": height}, targetOrigin);

On my site, I listen to this message and update the iframe’s height by code:

window.addEventListener("message", function (event) {
  if (event.data.height) {
    const iframe = document.getElementById("iframe");
    iframe.height = event.data.height;
  }
});

However clicking inside the iframe does not count as user interaction on the site, so by expanding the iframe from JavaScript it results as “unexpected layout shift” once the content below the iframe is pushed down.

I tried to delay the height change with setTimeout, and also added transition css rule to the iframe’s height, but still getting high CLS numbers. I also tried to add a button on the site and once the message arrives, I trigger a click event on it, and handle the resize from that, but it didn’t help at all.

I can ask the iframed site to modify their code, if necessary. Also the new height is dynamic, so I won’t know it until the message arrives.

How to solve the CLS issue, while having the resize in place?

How do I increase the storage of my VS code? My local host isn’t running at all and it keeps saying I’m at memory limit

I just ran my code as I usually do and it started taking so much time to output then after a while, it’ll fail and I’ll have to run it again but now, it’s just taking time and failing. No output so I can’t even see results of what I’m doing.

I tried chatGPT but I didn’t understand what it meant about expanding storage on VS code so here I am looking for more solutions.
This is what I’m getting
FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory and then some other lines I don’t understand

Ajax is preventing input type number min attribute

function Min(ID) {
    $Number = document.getElementById(ID);
    if ($Number.value < 1 && $Number.value !== "") {
        $Number.value = 1;
    }
}
echo '
<form id="' . $Item2 . '">
    <input type="image" src="AddToCart.png" style="margin:5px; float:left; font-size:25px;" width="65px" height="33" id="' . $EAN2 . '"
    onmouseup="KeyUp(this.id)" onmousedown="Click(this.id)"/>
    <input type="number" id = "' . $Image .'" name = "Amount" min="1" onKeyUp="Min(this.id)">
    <input type="text" name = "ID" value="' . $Item . '" readonly style="display: none;">
    <input type="text" name = "Cost" value="' . $Cost . '" readonly style="display: none;">
    <input type="text" name = "Kom" value="' . $Kom . '" readonly style="display: none;">
    <input type="text" name = "EAN" value="' . $EAN . '" readonly style="display: none;">
    <input type="text" name = "Type" value="Food/Slatko" readonly style="display: none;">
    <input type="text" name = "Image" value="' . $Image . '" readonly style="display: none;">
    <input type="text" name = "Account" value="' . $_SESSION["Account"] . '" readonly style="display: none;">
</form>';
<script>
echo "
<script>
$('#" . $EAN2 . "').on('click',function(event){
    event.preventDefault()
    $.ajax({
        type: 'get',
        url: 'ItemProcessor.php',
        data: $('#" . $Item2 . "').serialize(),
    })
})
</script>";

I have this form here. It normally stops the user from inputting less than 1 into the input, but because of the ajax code it sends it regardless.

I have tried adding a function onkeyup that checks the value and sets it to 1 if it’s lower than it, but the user can press the image while not releasing the key to still have a negative number.