Pass key/value pair into jest-mock-extended calledWith

I have this in one of my tests:

mock(stockReadOnlyRepository).fetch.calledWith(objectContainsValue({id: 'teststock1id'})).mockResolvedValue([{
    id: "teststock1id",
    symbol: "teststock1symbol",
    name: "teststock1name",
    value: 956.9,
    volume: 6000,
    open: 898.5,
    close: 967.2
}])

mock(stockReadOnlyRepository).fetch.calledWith({}, {lowestValue: true}).mockResolvedValue([{
    id: "teststock2id",
    symbol: "teststock2symbol",
    name: "teststock2name",
    value: 900,
    volume: 6000,
    open: 898.5,
    close: 967.2
}])

The second one works but the first just returns an undefined when i call that function with those parameters. How do I specify the {id: 'teststock1id'} object as the parameters for the first mock?

Is there a way to loop these 3 functions one by one on interval of 6 seconds?

So i have this task to constantly show 4 logos then 4 logos then 3 logos with 6 seconds interval between them. I made a function that shows first chunk of the 4 logos of the logos array. DO I need to call the function 3 times with diff array as an argument? What is the right way to do it ?

let logos = [
  {
    id: 1,
    img: "./img/apple.png",
  },
  {
    id: 2,
    img: "./img/instagram.jpg",
  },
  {
    id: 3,
    img: "./img/github.png",
  },
  {
    id: 4,
    img: "./img/google.png",
  },
  {
    id: 5,
    img: "./img/lyft.png",
  },
  {
    id: 6,
    img: "./img/paypal.png",
  },
  {
    id: 7,
    img: "./img/ripple.png",
  },
  {
    id: 8,
    img: "./img/spotify.png",
  },
  {
    id: 9,
    img: "./img/tesla.png",
  },
  {
    id: 10,
    img: "./img/uber.png",
  },
  {
    id: 11,
    img: "./img/youtube.png",
  },
];

//DOM 
const imageWrapper = document.querySelector('.logos-wrapper')
// const logo = document.createElement('div');

const firstArr = logos
// .map(logo => logo.img)
.slice(0, 4);
console.log(firstArr);

const secondArr = logos.slice(4, 8);
console.log(secondArr)  

const thirdArr = logos.slice(8, 11);
console.log(thirdArr)

function showLogos(firstArr) {
  for (let logo in firstArr) {
    imageWrapper.innerHTML += 
    `<div class="col-3 mb-3 logo-item">
    <img src="${firstArr[logo].img}"/>
    </div>`
  }
 }

showLogos(firstArr)
showLogos(secondArr)
showLogos(thirdArr)

PS: It’s a bonus if after every cycle of 4-4-3 they are shuffled

what is best method for translate language in javascript [closed]

I want to build a big great system and use multilanguage in it using Vanila JS, so I want to know the best method to do this (so fast and clean code).

I tried this way and I get a good result but it didn’t satisfy me, I think I should get better one.

at first I define translate function:

const translateWords = {
  en:{
   name: "Name",
  }
  fr:{
   name: "Nom"
  }
}

const lang = localStorage.getItem('userlang') || "fr";
function translate(word) {
    document.write(translateWords[lang][word])
}

also there is an HTML file

  <span class="boldText">
    <script>translate("name")</script>
  </span>

it right directly with load and with no delay.

setMeta in gutenberg block saves the meta value in multiple rows instead of one row

I am writing a gutenberg block which saves the data into meta fields. Problem is that the value is being saved in multiple rows in the database instead of one. How can I save in one row?

For example: ‘My apple’ is saved as metakeyname: My and metakeyname: apple into the database. I want to save it as metakeyname: My apple

Below is my code. Please help. Thank you!

const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { RichText, PlainText, MediaUpload, InspectorControls } = wp.editor;
const { TextControl, Tooltip, PanelBody, PanelRow, FormToggle, Button } = wp.components;
const el = wp.element.createElement;

registerBlockType('my/fields', {
    title: 'My Fields',
    description: 'Fill in the required data and press the Update button above',
    icon: 'products',
    category: 'common',
    attributes: {
        sku: {type: 'string'},
        
        pdf: {type: 'string'},
        gallery: {type: 'string'},
        features: {type: 'string'},
        brands: {type: 'string'},
        category: {type: 'string'},
    },
    
    edit: (props) => { 
    const { attributes, setAttributes } = props;
    const [meta, setMeta] = wp.coreData.useEntityProp('postType', 'post', 'meta');

        
return el(
  "div",
  null,
   el(
    "h3",
    null,
    "Please enter Product name above & details below"
  ),
   el(TextControl, {
    label: "SKU:",
    value: attributes.sku,
    onChange: (newtext) => setAttributes({ sku: newtext }) & setMeta({sku: newtext})        
  })
);
        
    },
    
    save: function(props) {
            return props.attributes.sku;
    }
    
})

Show Alert Before Loading Animation and Form Submission

I use the onsubmit function to show a loading animation before form submission.

How can I show an alert first before the loading animation triggers and before form submission?

Below is the sample code that shows the animation.

function ShowLoading() {
        var div = document.createElement("div");
        var img = document.createElement("img");
        // img.src = "";
        div.innerHTML = "<span style='color: white;  text-transform: uppercase; letter-spacing: 5px; font-size: 15px;'>SAVING</span><br/>  <img  src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoTaQ3jZMSSsQvJRcN7qvrEzdFbVCl6XiotnTroAox6-cjYrnJqtsFfZ3k94E5CULApvvl8z3EE_HAhqgAofLd5am4KvpNbEJZTL6-S6N24DjCxW_fBBGRguumQg_bSQVlQWDIcd0BFjXq8B0XAkLgX2qVCJ1xZCFjIIOKqjab8EbAe_aFgm94URoA/s1600/ezgif.com-gif-maker%20%283%29.gif" width="226px" height="22px">";
        div.style.cssText =
          "position: fixed; top: 50%; left: 50%; z-index: 5000; width: auto; text-align: center; background: #b51200; border: 2px solid #b51200;  border-radius: 7px; transform: translate(-50%,-50%)";
        // div.appendChild(img);
        document.body.appendChild(div);
  event.preventDefault();
        // These 2 lines cancel form submission, so only use if needed.
        //window.event.cancelBubble = true;
        //e.stopPropagation();
      }
<form action='' method='POST' runat="server" id="theForm"  onsubmit="ShowLoading()">

 <input name='Name' placeholder='Full Name' required='' type='text'/>

<button href='/' type='submit' id="submitForm">Submit</button>
</form>

Below was my solution (NOT WORKING).

function ShowLoading() {
        var div = document.createElement("div");
        var img = document.createElement("img");
       
       alert("You are about to submit this form");
.then((value) => {

        div.innerHTML = "<span style='color: white;  text-transform: uppercase; letter-spacing: 5px; font-size: 15px;'>SAVING</span><br/>  <img  src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjoTaQ3jZMSSsQvJRcN7qvrEzdFbVCl6XiotnTroAox6-cjYrnJqtsFfZ3k94E5CULApvvl8z3EE_HAhqgAofLd5am4KvpNbEJZTL6-S6N24DjCxW_fBBGRguumQg_bSQVlQWDIcd0BFjXq8B0XAkLgX2qVCJ1xZCFjIIOKqjab8EbAe_aFgm94URoA/s1600/ezgif.com-gif-maker%20%283%29.gif" width="226px" height="22px">";
        div.style.cssText =
          "position: fixed; top: 50%; left: 50%; z-index: 5000; width: auto; text-align: center; background: #b51200; border: 2px solid #b51200;  border-radius: 7px; transform: translate(-50%,-50%)";
        // div.appendChild(img);
        document.body.appendChild(div);
  event.preventDefault();
        // These 2 lines cancel form submission, so only use if needed.
        //window.event.cancelBubble = true;
        //e.stopPropagation();
      }
<form action='' method='POST' runat="server" id="theForm"  onsubmit="ShowLoading()">

 <input name='Name' placeholder='Full Name' required='' type='text'/>

<button href='/' type='submit' id="submitForm">Submit</button>
</form>

How to print javascript variables and show them in console?

I’m trying to implement google ads conversion on my website and as per the google team, I added the tags they gave yet the conversion is not showing up properly.

After getting in touch with one of the team members, he told me to correct the code:

So far My code:

  • I m passing an email value through the URL to the ‘Thank-you’ page.
  • I m echoing the value inside a hidden input tag and calling it back using ID in javascript
  • I can get the value from the input and print it in the console.
<input type="hidden" id="email_for_ads" value="[email protected]">
<script>
  var email_for_ads = $("#email_for_ads").val();
  var enhanced_conversion_data = {
    "email": email_for_ads
  };
    console.log(email_for_ads);
</script>

I can see the email id in the console, and I’m sure the value is being fetched.

But he said it should be like below upon inspect :

<input type="hidden" id="email_for_ads" value="[email protected]">

<script>
  var email_for_ads = $("#email_for_ads").val();
  var enhanced_conversion_data = {
    "email": "[email protected]"
  };
    console.log("[email protected]");
</script>

I even tried the below code too

var baseUrl = (window.location).href; // You can also use document.URL
  var email_for_ads = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
  //var email_for_ads = $("#email_for_ads").val();
  var enhanced_conversion_data = {
    "email": email_for_ads
  };
    console.log(email_for_ads);

yet the same output. I can see the value in the console but on inspect. But he insists that it is that way and could be able to see the email value directly in inspecting itself.

Can someone understand, whether this is possible, if so, how can i do it.

JS AJAX for passing checkbox values into DB

I have working ajax code for passing text values into DB. Now I have improved my form with a pair of checkboxes (chk1, chk2). How to adapt them into my ajax code?

    $(function(){
        $('#register').click(function(e){

            var valid = this.form.checkValidity();

            if(valid){

            var var1    = $('#var1').val();
            var var2   = $('#var2').val();
            var var3 = $('#var3').val();
            var var4    = $('#var4').val();

                e.preventDefault(); 
            
                $.ajax({
                    type: 'POST',
                    url: 'process.php',
                    data: {var1: var1, var2: var2, var3: var3, var4: var4},
                    
    success: function (data) {
        if (data !== 'error') {
Swal.fire({
                                'title': 'Success',
                                'type': 'success',
                    });     
                
        } else {
Swal.fire({
                                'title': 'Error',
                                'type': 'error',
                                })  
        }
    }
});
            }else{
             
            }
        });     
    });

How to create a new prose class that extends tailwind’s typography prose class?

Tailwind’s typography plugin provides prose class which is good to implement markdown like styling.

I want to create another class which overrides some of the styling of this prose class but not mutate the original prose class.

And I want to do this inside tailwind.config.js since I use css-in-js styling and no global css file.

Suppose I currently use prose (provided by tailwind) to apply styles to nested blockquote and code elements.

I would want to use a new custom-prose class with new styling for say nested blockquote but retaining the old styling for nested code inside the prose.

So yes looking for a composable way of doing this. custom-prose should keep applying prose styling where it’s not overridden.

Any tips on how to achieve the same ?

Why doesn’t my code alert something despite adding a verification script already?

I’d like to ask why my code doesn’t alert anything when I leave the “name” form blank. I think I wrote down the write variables/names though, but it still doesn’t work.

<div class="regi-01">
            <label for="name"></label>
            <div>
                <input id="name" name="form01" type="text" autocomplete="off" placeholder="What's your name?">
            </div><br>
        </div>
        <br>

<script>
if( document.getElementById.name.value == "" ) {
 alert( "Please provide your name!" );
 return false;
 }
</script>

Google Maps API place marker over POI

I’m creating a marker based on onClick event from PoI.
After fetching data I want to place marker that will replace PoI (same behavior as Google Maps web)
For example Strawberry fields PoI is not visible when it’s selected and the marker is creating over it (https://g.page/strawberry-fields-central-park?share)

Creating a marker

var marker = new google.maps.Marker({
  position: event.latLng,
  map: map,
});

How to hide specific PoI when creating a marker?

Function Expression (JavaScript)

Convert the function named functionDeclaration to an anonymous function expression and assign it to a variable called myFunc.

function functionDeclaration() {
  let myFunc = str
   return "Hi there!";

}

console.log(myFunc())

I’m new to coding. What am I doing wrong? It’s supposed to print ‘Hi there!’ but keeps giving me a reference error message.

Thank you for your help!

Trying to set a mouse hover function to change color of divs when using .foreach

im trying to have a .for each function that turns divs red when my mouse hovers over them. this is what i have so far:

canvas = document.getElementById('canvas');
boxes = document.querySelectorAll('div');

for (i=0; i<=2000; i++) {
    const box = document.createElement('div')
    box.classList.add('pixel')
    canvas.appendChild(box)
}

boxes.forEach((pixel) => {
    addEventListener('mouseover', function() {
        setTimeout(pixel.classList.add('red'), 5000);
    })
});

Get error 403 when using NextJS Image Component

I’m trying to render an image using Next JS Image component. The image are located at public/images/imageName.png. When I tried to load the image, an alt text is shown instead of the image itself. In my console, there is this error:

GET https://aria.arvis-engineering.net/_next/static/image/public/images/sag.698ed38ac6aad899e5e6dbf22df2c717.png?auto=format&fit=max&w=256 403

This error happened to most of the images rendered (3 out of 4 images). Any idea on how to solve this problem?

Thank you, really appreciate your help

How to convert image buffer to file object in NodeJS?

Purpose

How do I make a file in the same path in NodeJS in the same form as client request form?

// test.js 
const readFile = fs.readFileSync(filepath, (err, data) => {
if (err) {
    console.log(err)
} else {
    return data
} })
// result : <Buffer 89 50 4e 47 0d 0a 1a 0a ..... >
mysdk(readFile)
// error : it need to file name, size(bytes) , type ...

I want File object like this.

enter image description here

File locate

enter image description here