Is it possible to assert a failure in a Cypress Custom command?

How do I assert a failure from a Cypress Custom Command? Let’s say I have a custom command with a complex set of tests that can fail due to some elements not being found, can I assert the failure of that line in a test file?

e2e/test.cy.ts:

cy.someComplexCommand().should('fail')

support/commands.ts:


Cypress.Commands.add('someComplexCommand', () => {

  /* Some detailed DOM-traversing test */

})

The above is obviously sudo-code. The use case for this is that I have a complicated command that searches for a particular row in a table based on its’ text content. While I use this most of the time to assert that something exists in the table, there are some tests that need to assert that it doesn’t exist (like when I have just deleted the table row in the UI). Rather than write another command or more code in the test body, I’d prefer to keep it DRY and re-use the existing command, asserting a failure. Is this possible?

I’ve searched and there doesn’t seem to be a lot of detail about asserting failures in Cypress.

Real world example

support/commands.ts:

Cypress.Commands.add('getTableRowContainingText', (text: string): Cypress.Chainable<JQuery<HTMLElement>> => {

  return cy.get('table')
    .first()
    .find('tbody > tr > td')
    .filter(`:contains(${text})`)
    .first()
    .parent('tr')

})

e2e/test.cy.ts:

cy.getTableRowContainingText('not-there').should('not.exist')

The above test fails because when a table is empty, my UI doesn’t show a table at all:

enter image description here

Javascript listener mousemove giving wrong position to custom cursor

I’m pulling a late nighter trying like crazy to get the last bugs out of a site I’m updating & I am just about ready to pull my hair out over this one.

https://thebluehouseny.com/menu/

If you scroll down the page a little, you will see I am implementing a system where the client can upload their own image’s for the restaurant’s weekly menus. Everything is going swimmingly there, but I am trying to make it so when the user hovers over the left or right side of the menu image, it displays the custom arrow cursor with it’s specific direction related class. We’re still good there. The problem is two things,

  1. The custom cursor (arrow) is not staying within the confines of the menu image area. Seems like a dumb thing, but it is tripping out my OCD watching this custom cursor going outside the image it’s supposed to be navigating behind it.
  2. And much MUCH more important, and crucial… I can NOT seem to get the custom cursor to display in the proper location. No matter what, it is always offset way to the right and way down from where the actual user’s mouse is. No good. This is the bigger of the two requirements that I can’t get figured out.
var swiper = new Swiper('.swiper-container', {
        slidesPerView: 1,
        loop: true,
        speed: 0,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
      });
      let cursor = document.querySelector('.arrow-cursor');
      document.addEventListener('mousemove', moveCursor);
      function moveCursor(e) {
        let x = e.clientX;
        let y = e.clientY;

        cursor.style.left = `${x}px`;
        cursor.style.top = `${y}px`;
      }
      let links = Array.from(document.querySelectorAll('.swiper-button-ctrl'));
      links.forEach((link) => {
        link.addEventListener('mouseover', () => {
          if (link.classList.contains('swiper-button-prev')) {
            cursor.classList.remove('cursor-next');
            cursor.classList.add('cursor-prev');
          }
          if (link.classList.contains('swiper-button-next')) {
            cursor.classList.remove('cursor-prev');
            cursor.classList.add('cursor-next');
          }
          cursor.classList.add('active');
        });
        link.addEventListener('mouseleave', () => {
          if (link.classList.contains('swiper-button-prev')) {
            cursor.classList.remove('cursor-prev');
          }
          if (link.classList.contains('swiper-button-next')) {
            cursor.classList.remove('cursor-next');
          }
          cursor.classList.remove('active');
        });
      });

Above is the area of the javascript where I set up the event listener and call for the custom classes and cursor placement… but ISSUES! 🙁

Any and ALL help appreciated. The site uses both standard javascript & jQuery.

Forge viewer – Custom Model Fragments position is changed after adding

I’m adding a custom model with a number of meshes to the Forge viewer using this code

let cameras = camerasJSON.cameras[0];
let sceneBuilder = await viewer.loadExtension('Autodesk.Viewing.SceneBuilder');
let modelBuilder = await sceneBuilder.addNewModel({
    modelNameOverride: 'Cameras',
    conserveMemory: false
})
cameras.forEach(camera => {
    const sphereGeometry = new THREE.BufferGeometry().fromGeometry(new THREE.SphereGeometry(1, 8, 8));
    const sphereMaterial = new THREE.MeshPhongMaterial({ color: new THREE.Color(0, 1, 0) });
    let p = [+camera[2]/1000, +camera[3]/1000, +camera[4]/1000]
    const sphereTransform = new THREE.Matrix4().compose(
        new THREE.Vector3(...p),
        new THREE.Quaternion(0,0,0,1),
        new THREE.Vector3(1, 1, 1)
    );
        
    let mesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
    mesh.matrix = sphereTransform
    mesh.dbId = camera[0].split('_')[1];    
    modelBuilder.addMesh(mesh);
})

Then I try to retrieve position of a clicked fragment using this code

event.selections[0].model.getInstanceTree().enumNodeFragments(event.selections[0].dbIdArray[0], function (frag) {       
    let fragProxy = viewer.impl.getFragmentProxy(viewer.model, frag);
    let matrix = new THREE.Matrix4();       
    fragProxy.getWorldMatrix(matrix);       
    let position = new THREE.Vector3().setFromMatrixPosition(matrix);
    console.log(position);
});

Retrieved position (and transform matrix itself) do not match to the initial position. Created meshes (green) are located correctly. But the actual fragment positions (red) do not match even relatively. Model is exploded for visibility.

Image

Removing global offset does not seem to have any effect.

Not sure if I’m retrieving position incorrectly, or the fragment’s position is somehow transformed during adding. The main model does not have such issue.

Can not get a subelement in a jQuery Ajax response

Good. evening. I have a Laravel 10 blade template, and in a certain point I am calling a jQuery Ajax function when a tab is clicked, I receiving an HTML response. but when I try to get a sub-element from that response it returns undefined. here is the HTML code, and the JavaScript function:

  @extends('layouts.base')

    @section('content')
    <div class="payer-container" style="margin-top: 6%;">

    <div class="row">
        <div class="col-12">
            <div class="card mb-4 mx-4">
                <div class="card-header pb-0">
                    <div class="d-flex flex-row justify-content-between">
                        <div>
                            <h5 class="my-6 font-weight-bold text-secondary">All Payable</h5>
                        </div>
                    </div>
                </div>
                <div class="card-body px-0 pt-0 pb-2">
                    <ul class="nav nav-tabs" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link has-outstanding active " data-tag="tag-content-1" id="tab-1" data-bs-toggle="tab" href="/payers/outstanding" role="tab" aria-selected="false">

                                <span class="d-none d-sm-block font-weight-bold text-capitalized text-xs">Outstanding</span>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link has-payed" id="tab-2" data-tag="tag-content-2" data-bs-toggle="tab" href="/payers/payed" role="tab" aria-selected="true">

                                <span class="d-none d-sm-block font-weight-bold text-capitalized text-xs">Payed</span>
                            </a>
                        </li>
                    </ul>

                    <div class="table-responsive p-0">
                        <table class="table align-items-center mb-0 table-hover table-align-middle w-100">


                    </div>



                    <thead class="table-light">

                        <tr>
                            <th class="text-capitalized text-secondary text-xxs font-weight-bolder opacity-7">
                                Reference #
                            </th>
                            <th class="text-capitalized text-secondary text-xxs font-weight-bolder opacity-7">
                                Due date
                            </th>
                            <th class="text-center text-capitalized text-secondary text-xxs font-weight-bolder opacity-7">
                                Company name
                            </th>
                            <th class="text-capitalized text-secondary text-xxs font-weight-bolder opacity-7 ps-2">
                                Initial amount
                            </th>
                            <th class="text-center text-capitalized text-secondary text-xxs font-weight-bolder opacity-7">
                                Outstanding amount
                            </th>
                            <th class="text-center text-capitalized text-secondary text-xxs font-weight-bolder opacity-7">
                                Options
                            </th>
                        </tr>
                    </thead>
                    <tbody>


                        <div class="tab-content" style="visibility: visible">
                            @if ($payments)
                            @foreach ($payments as $payment)
                            <tr>
                                <td class="ps-4">
                                    <p class="text-xs font-weight-bold mb-0">{{ $payment["reference_id"] }}</p>
                                </td>
                                <td class="ps-4">
                                    <p class="text-xs font-weight-bold mb-0">{{ $payment["due_date"] }}</p>
                                </td>
                                <td class="text-center">
                                    <p class="text-xs font-weight-bold text-capitalized mb-0">{{ $payment["creditor_id"] }}</p>
                                </td>
                                <td class="text-left">
                                    <p class="text-xs font-weight-bold mb-0">{{$payment["currency"]}} {{ $payment["initial_amount"] }}</p>
                                </td>
                                <td class="text-center">
                                    <p class="text-xs font-weight-bold mb-0">{{$payment["currency"]}} {{ $payment["outstanding_amount"] }}</p>
                                </td>
                                <td class="text-center">
                                    <p class="text-xs font-weight-light mb-0">
                                        <i class="fa fa-download"> <a href=""></a></i>
                                        @if ($payment['status'] == 'unPaid')
                                        <button class="payer-button" type="submit" style="width: auto; padding:2px; border-radius: 10px; background-color: #ff6321; color: white;">Pay Now</button>
                                        @endif
                                    </p>
                                </td>

                            </tr>
                            @endforeach
                            @endif
                        </div>






                    </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
@endsection

 
      @push('scripts')
    <script>
    $('.nav-link').click(function() {
        $('.nav-link').removeClass('active');
        $(this).addClass('active');
        let url = $(this).attr('href');

        let tabContentElement = $('.payer-container');




        $.ajax({
                method: 'GET',
                url: url
            })
            .done(function(response) {
                let newContent = $(response).filter('.tab-content').html();
                alert(newContent);
                tabContentElement.html(newContent);
            })

        .fail(function() {
            console.log("Error");
        });

        return false;

        });
      </script>
       @endpush

Thanks so much in advance. and have a nice day.

video stop when visibilitychange with jmuxer

i’m using jmuxer to play camera video in real time and we are in the process of drawing a video frame on a canvas.
however, when return after minimizing Chrome, the function for jmuxer feed works, but the video does not play.

this is parser code

const messageParser = (event) => {
  console.log("message parser");
  const origin = event.data;
  const headerValue = new Uint8Array(origin.slice(0, 2));
  const jsonSize = new DataView(origin.slice(14, 18)).getInt32() + 18;
  let lastByte = jsonSize;

  if (headerValue[1] === 126) {
    const jsonData = JSON.parse(
      new TextDecoder().decode(origin.slice(18, jsonSize))
    );

    jsonData.Image.forEach((item) => {
      streamInfo.fps = item.Draw.FPS;
      streamInfo.signalData[streamInfo.frame] = item.Draw
        ? item.Draw.Light
        : "";
      streamInfo.metaData[streamInfo.frame++] =
        item.Draw && item.Draw.Object ? item.Draw.Object : new Array();

      switch (item.Format) {
        case "h264": {
          processH264Format(item, origin, lastByte);

          break;
        }

        case "jpeg": {
          // const jpegData = origin.slice(lastByte, (lastByte += item.FrameLength));
          // this.drawFrameHandler(ch, )
          break;
        }
      }
    });
  } else {
    return;
  }
};

we also checked the following to see if the video was paused

 document.addEventListener("visibilitychange", () => {
    const isVisible = document.visibilityState === "visible";
    if (isVisible) {
      console.log(screenPlayer.value.paused);
      drawInterval.value = window.setInterval(() => {
        drawFrame();
      }, streamInfo.duration);
    } else {
      clearInterval(drawInterval.value);
    }
    booleanOptions.isFocus = isVisible;
  });

the parser is still running and passing the feed to jmuxer, but why isn’t the video playing?

we confirmed that the function that parses video data still works, and also checked the video pause status according to visibility.

How would I add array inside square bracket []

I have an array which returns values like this

let arr = {Routing Category: 'new', TimeSlice: 'AM', Destination1: 'test', Value1: '701', Destination2: 'Test'}

but I want to wrap this array inside [] bracket like this

[{Routing Category: 'new', TimeSlice: 'AM', Destination1: 'test', Value1: '701', Destination2: 'Test'}]

How would I do that. Please help

I was pushing this array into new array but that was returning as object object.

Save a Bookmark which can open 2 URLs one after another

Is it possible to save a bookmark with 2 URLs ? Upon clicking on the bookmark, the first URL should be opened first and after a brief pause the second URL is opened in the same window.

E.g. First I want to open the link https://stackoverflow.com/ and after 5 seconds I want to open 2nd URL https://stackoverflow.com/questions/ask automatically in the same window.

I know we can directly open the 2nd URL but I have some dependency on 1st URL hence don’t want to skip it.

Log display value but function not return this value

Value offered is displayed in console.log but not in result of function.

Example: console.log(result) returns {…, offered: true} (with offered)
return result returns {…} (without offered)

async findAllByCategory(category_id: number, user_uuid: string, order_status_id?: number): Promise<OrderResponse[]> {
    try {
      const orders = await this.orderRepository.findAll({
        where: { category_id, order_status_id: order_status_id ?? [1, 2, 3] },
        ...this.orderInclude,
      })

      const createdChats = await this.chatService.findMy(user_uuid)

      const result = []
      for (const order of orders) {
        const findChat = createdChats.findIndex((value) => value.order_uuid == order.order_uuid)
        order['offered'] = findChat !== -1

        result.push(order)
      }

      console.log(result) // field offered is exists

      return result // field offered doesn't exists
    } catch (error) {
      throw new Error(error)
    }
  }

remix ide – The blue compilot icon is disabled. Do you know what to do?

The blue compilot icon is disabled. Do you know what to do?
The code was scraped from what a YouTuber posted as open source.
Is this because there is an error somewhere in the code?

We are trying to create 3 billion coins called kal.a based on bnb.

I scraped the code from an open source posted by a YouTuber.
However, the YouTuber is not a developer (it appears to have been written around July 2023 through chat gpt)

I have no development knowledge, so I don’t know where the error occurred.

calling a function from an external js file in vue

I’m trying to integrate a payment gateway in my website. They provided a plugin and I have to use one of the function from their plugin file which is AbaPayway.checkout(). However I’m getting AbaPayway is not defined when I call it from my vue component. I defined their plugin in the head tag of the index.html file. How do I call the function?

my index.html file

<!DOCTYPE html>
<html lang="">
  <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" />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <script src="https://checkout.payway.com.kh/plugins/checkout2-0.js"></script>
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>

  <body>
    <noscript>
      <strong
        >We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work
        properly without JavaScript enabled. Please enable it to
        continue.</strong
      >
    </noscript>
    <div id="app"></div>
  </body>
</html>

This is my vue component

<template>
<div>
<button @click="buy"></button>
<div id="aba_main_modal" class="aba-modal-desktop" style="display: none;">
            <div class="aba-checkout-modal-content">
                <form method="GET" target="aba_webservice" :action="paymentHtmlContent" id="aba_merchant_request">
                    <!-- Form content will be dynamically appended here -->
                </form>
            </div>
        </div>
</div>
</template>

<script>
export default {
    methods: {
    buy() {
        const newItem = {
          id: this.Id,
        };
        axios
          .post(
            `${process.env.VUE_APP_API_ENDPOINT}/transact/createsingleorder`,
            {
              items: newItem,
            }
          )
          .then((response) => {
            if (response.data) {
              this.paymentHtmlContent = response.data.data;
              AbaPayway.checkout() //calling the function from this line
            }
          })
          .catch((error) => {
            console.error("Purchase failed:", error);
          });
        },
    },
}
</script>

Node modules is not getting installed in my dir. why?? Can anyone explain what is happening in bash terminal?

(Git bash terminal severity vulnerabilities node modules is not
getting installed
.

Why there is high severity vulnerabilities.?
Even if there is no node modules in my dir.

I ran the command npm audit fix.

Showing severity of high risk.[git bash[git bashgit bash](https://i.stack.imgur.com/SsSaI.jpg)](https://i.stack.imgur.com/vdqAV.jpg)

How to show click count number received from mysql database on my website?

I am creating website which posts links to the other websites. And I want to show the total number of visit right below the links.

For example,

website link
100 visit

I figured out the way to count click on the anchor tag and increment the click_count value in the mysql database.However, I still cannot figure out how to get the click_count value from the mysql database table and update number of visit in the website. I don’t want the number of visit to be reset when the website is updated.

For example,

website link
100 visit

after someone clicks the link and come back to my webpage. I want my webpage to look like

website link
101 visit

Import a node module in a content script of a Chrome extension (Vite and react)

I am trying to import the axe-core package into my content script so that I can do axe. run in a web context.

I am sending message to content script using chrome.scripting API

I have downloaded axe.min.js and placed it inside the assets folder.

content_script.js

chrome.runtime.onMessage.addListener(
  async function (request, _, sendResponse) {

    console.log('On Message');

    if (request.message === "getDOM") {
      try {
        console.log('REQUEST FOUND')

        const src = chrome.runtime.getURL("src/assets/runAxe.js");
        const axeMain = await import(src);
         
        axeMain.runAxe()
      } catch (e) {
        console.log('ERROR FOUND ON MESSAGE');
        console.log(e);
      }
     
       sendResponse({ response: 'Hello' });
    }

    
  }
);

src/assets/runAxe.js

import {axe} from './axe.min.js'
export default async function runAxe() {
    const r = await axe.run();

    console.log('==== Results in runAxe')
    console.log(r);
    
}

manifest.json (part of manifest)

 "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "./src/chrome/content_script.js"
            ]
        }
    ],
   
    "web_accessible_resources": [{
        "matches": ["<all_urls>"],
        "resources": [
            "src/assets/*",
            "src/assets/axe-core/*"
        ]
      }],
    "host_permissions": [
        "https://*/*",
        "http://*/*"
    ]

Trying to make the axe-core package available on the content script

TypeError: UpdateCommand is not a constructor – AWS SDK v3 for nodejs unit test with jest

I keep getting “TypeError: UpdateCommand is not a constructor” when the unit test reaches the stage where it is calling the UpdateCommand from @aws-sdk/lib-dynamodb. I think it is the mock that has issue. Not really sure where to go from here

jest.mock('@aws-sdk/client-dynamodb', () => {
    return {
      DynamoDBClient: jest.fn().mockImplementation(() => {
        return {}
      }),
    };
  });
  jest.mock('@aws-sdk/lib-dynamodb', () => {
    return {
      DynamoDBDocumentClient: {
        from: jest.fn().mockImplementation(() => {
          return {
            send: jest.fn().mockImplementation((command) => {
              let res = ''
              if (command.name === 'GetCommand') {
                res = {
                  Item: {
                    data: 'data',
                  }
                }
              }else if (command.name === 'UpdateCommand' || command.name === 'PutCommand') {
                res = { TableName: 'tableName', Item: { PK: 'pk', SK: 'sk' } }
              }
              else if (command.name === 'QueryCommand') {
                res = {
                  Items:[
                  {
                      "data":"data"
                  }
                ]
              }
              }
              return Promise.resolve(res)
            })
          }
        })
      },
      GetCommand: jest.fn().mockImplementation((cmdPayload) => {
        if (cmdPayload.Key.PK === 'pk') {
          return { name: 'GetCommand' }
        }
        return undefined
      }),
      PutCommand: jest.fn().mockImplementation(() => {
        return { name: 'PutCommand' }
      }),
      UpdateCommand: jest.fn().mockImplementation((cmdPayload) => {
        return { name: 'UpdateCommand' }
      }),
      QueryCommand: jest.fn().mockImplementation((cmdPayload) => {
        // ensure valid api name in mock table
        if (cmdPayload.ExpressionAttributeValues[':ct'] === 'test') {
          return { name: 'QueryCommand' }
        }
        return undefined
      })

    }
})

Tried clean npm install but no luck. Would really appreciate any inputs on this.

Thanks in advance!

String Replace first line and last line

I have the following string returned by my system as xml

<select>
<unsubscriptionLink deliveryId="1639" recipientId="76391"/>
<unsubscriptionLink deliveryId="49308" recipientId="76391"/>
<unsubscriptionLink deliveryId="2447" recipientId="76391"/>
<unsubscriptionLink deliveryId="9225" recipientId="76391"/>
<unsubscriptionLink deliveryId="24527" recipientId="76391"/>
</select>

I need the parent select element to match the following.

<unsubscriptionLink-collection xtkschema="nms:unsubscriptionLink">
    <unsubscriptionLink deliveryId="4151" recipientId="1000" url="http://www.google.com"/>
    <unsubscriptionLink deliveryId="4151" recipientId="1030" url="http://www.google.com"/>
    <unsubscriptionLink deliveryId="4151" recipientId="1031" url="http://www.google.com"/>
    <unsubscriptionLink deliveryId="4151" recipientId="1060" url="http://www.google.com"/>
    <unsubscriptionLink deliveryId="4151" recipientId="1090" url="http://www.google.com"/>
</unsubscriptionLink-collection>

Is there a way to replace the first ocurrence of select to match <unsubscriptionLink-collection xtkschema="nms:unsubscriptionLink">

And also the last line </select> to </unsubscriptionLink-collection> I can only use javascript.also, the complete number of items will be 10k rows, so rather than scanning the whole payload, Is better to focus on finding the first line select and the last line select. (does javascript allow to scan from back to front and front to back using regex?)

response