How to create an automatic mock for built-in objects (Jest, Vanilla JS)

I know that with Jest you can create an automatic class mock for an ES6 class. You can do that by calling jest.mock() with the filename as parameter, like shown below:

import ClassThatShouldBeMocked from "./path/to/the/file.js";

jest.mock("./path/to/the/file.js");

// ClassThatShouldBeMocked is now mocked

But in my case I want to mock built-in objects like HTMLElement or CanvasRenderingContext2D. How do I get the path of such built-in objects? Is there another way to achieve an automatic mock in this case?


Currently I’m using jest.spyOn() to create an spy function for each method of this class, that is called in my code. This works but takes up much more time and effort, when I have to call many functions and methods every time.

Chrome Extensions and CSP

I have a popular Chrome Extension that fails on sites using CSP.

The extension enriches content on the sites my users visit, according to some settings they have configured.

On sites with a CSP policy, I get the following error when executing JS: This document requires 'TrustedScriptURL' assignment

How can I run my extension on these sites – can I use the site’s CSP f.ex., or would that be bad practice?

Multiple Word Counters For Multiple Divs

For my wordlist website I’m trying to make a automatic word counter for every list. I’m able to count the words of one list but when I add more the counter counts all the lists. I can’t find a solution anywhere so all help is greatly appreciated.

The editor of stack overflow is showing a error but the fiddle works:
http://jsfiddle.net/ge7akmzj/

$(function() {
    var text = $('.input').text();
    var wordsCount = text.split(',').length;
    $('.output').html('word count:' + wordsCount);
});
  <span class="input">
  These, are, 7, words, as, a, demonstration
  </span>
<br>
<br>
  <span class='output'>
  </span>
<br>
<br>
  <span class="input">
  These, are, 7, words, as, a, demonstration
  </span>
<br>
<br>
  <span class='output'>
  </span>

Wait for QueryParams, Inputs and Subscriptions

It’s been several times where I have coded solutions followed by 1000 fixes when in an Angular project I find myself having to listen to several events spread over time due to Angular life cycles, time to execute of some functions, and all that in order to execute a single action.

I don’t know if it is possible using the APIs provided by Angular and even RxJs to achieve my goals.

My question:

How should it go about waiting for a page’s QueryParams response, while waiting for some @inputs provided by that page and waiting for a subscription’s response.

Is it a design error?
Is there an easier solution than testing all possible cases?

I would appreciate your answers, Regards

Component only accepts specific colours (nextjs/react + tailwind)

I have an alert component which gets the prop alert_type based on which it should change it’s icon and colour. When I pass ‘good’ or ‘warn’ it works fine but if I pass ‘bad’ it does not accept the colour red. Further when I just edit the colour (both on ‘good’ and on ‘bad’) to be ‘red’ or any other color it does not work except ‘yellow’ and ‘green’ always work. How can this be?

/* This example requires Tailwind CSS v2.0+ */
import {
  CheckCircleIcon,
  ExclamationIcon,
  XCircleIcon,
} from '@heroicons/react/solid'

interface AlertProps {
  title: string
  alert_type?: string
  children?: React.ReactNode
}

export function Alert({ title, alert_type = 'good', children }: AlertProps) {
  const [colour, Icon] = (() => {
    switch (alert_type) {
      case 'good':
        return ['green', CheckCircleIcon]
      case 'warn':
        return ['yellow', ExclamationIcon]
      case 'bad':
        return ['red', XCircleIcon]
      default:
        return ['green', CheckCircleIcon]
    }
  })()

  const colours = {
    bg: 'bg-' + colour + '-50',
    icon: 'text-' + colour + '-400',
    title: 'text-' + colour + '-800',
    content: 'text-' + colour + '-700',
  }

  return (
    <div className={'rounded-md p-4 ' + colours.bg}>
      <div className="flex">
        <div className="flex-shrink-0">
          <Icon className={'h-5 w-5 ' + colours.icon} aria-hidden="true" />
        </div>
        <div className="ml-3">
          <h3 className={'text-sm font-medium ' + colours.title}>{title}</h3>
          <div className={'mt-2 text-sm ' + colours.content}>{children}</div>
        </div>
      </div>
    </div>
  )
}

Datatables auto refresh function doesn’t work

i have an issue with the reload function for datatables.

I am using the following code to load and reload the table (server-sided).

    $( document ).ready(function() {
    $('#dienst_tabelle').DataTable( {
        "ajax": "getData.php",
        "serverSide": true,
        "bProcessing": true,
        "bPaginate":false,
        "searching": false,
        "paging": false, 
        "info": false,
        "columns": [
            { mData: 'dienstname' } ,
            { mData: 'tagesart' },
            { mData: 'gueltig_am' },
            { mData: 'dienstbeginn' },
            { mData: 'dienstende' },
            { mData: 'zeit' },
            { mData: 'status' },
            { mData: 'button' }
        ]
    });

    setTimeout(function(){
        $('#dienst_tabelle').DataTable().ajax.reload(null, false);
    }, 3000);
});

The table loads succesfully, but the reload-function doesn’t do anything…

What i’m am doing wrong?

Thx

memo_serif

Why is the async function execution executed synchronously [duplicate]

enter image description here
enter image description here

const c = async() => console.log("2")
const a = async() => {
  console.log("1")
  await c()
  console.log("4")
}
const b = () => console.log("3");
console.log("start")
a();
b();

I would expect the sequence here to be 3 1 4 2, but apparently it is not. Async function seem to execute synchronously and be added to the callstack UNTIL they return, and that is when the rest is added to the event queue. Why is that and why is it not instantly added to the event queue?

Link to ECMA spec & other reads also greatly appreciated

Unhandled Rejection (TypeError): can’t access property “country”, this.props is undefined

i’m working on a react app

when run this function by infinite scroll i’ll get error

Unhandled Rejection (TypeError): can’t access property “country”,
this.props is undefined

async pageUpdater() {
  let url = `https://newsapi.org/v2/top-headlines?country=${this.props.country}&category=${this.props.category}&apiKey=myapi&page=${this.state.page}&pageSize=${this.props.pageSize}`;
  this.setState({ loading: true })
  await fetch(url).then(response => response.json()).then(data => {
    this.setState({ articles: data.articles, totalResults: data.totalResults, loading: false })
  })
}

how to get file details of uploaded file in extJS

how to get file details of uploaded file in extJS

I am using file upload and I need to first conveert into Grid and then sumbit.

for grid conversion I have to take all files details like this :

File {
    webkitRelativePath: "", 
    lastModifiedDate: Tue Jul 14 2009 11:02:31 GMT+0530 (India Standard Time), 
    name: "file.xlsx", 
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 
    size: 780831
 }

and here I am converting this to excell..

function handleFileSelect(evt){
    var files = evt.target.files;
    SessionConstant.uploadFileName = files[0].name;
    var xl2json = new ExcelToJSON();
    xl2json.parseExcel(files[0]);
   
   // Next code  
}


function ExcelToJSON  () {
    this.parseExcel = function(file) {
        var reader = new FileReader();

        reader.onload = function(e) {
          var data = e.target.result;
          var workbook = XLSX.read(data, {
            type: 'binary'
          });
          var uploadata = [];
          workbook.SheetNames.forEach(function(sheetName) {
           var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
            var json_object = JSON.stringify(XL_row_object);
            console.log(JSON.parse(json_object));
            uploadata.push(JSON.parse(json_object));
            jQuery( '#xlx_json' ).val( json_object );
          });
           var uploadData = uploadata;

        };

        reader.onerror = function(ex) {
          console.log(ex);
        };

        reader.readAsBinaryString(file);
      };
};

so this code when I am doing by using this

{
    text:'Upload',
    handler : function(){
        var x = document.createElement("INPUT");
            x.setAttribute("type", "file");
            x.setAttribute("id","upload");

            document.body.appendChild(x);
            document.getElementById('upload').addEventListener('change', handleFileSelect, false);
            document.getElementById('upload').click();

        
    },
}

This is working fine.

Now If I want to implement same thing fileupload in extJS so I can submit my form :

{
    xtype: 'filefield',
    cls:'common-fileupload',
    itemId:'fileUploadId',
    clearOnSubmit:false,
    width:300,
    labelWidth : '0',
    name: 'myFile',
    buttonConfig: {
        text: 'Browse',
        height : 30
    },
    listeners: {
        change: function(fld, value) {
           var newValue = value.replace(/C:\fakepath\/g, '');
            fld.setRawValue(newValue);
            this.up().submit({
                url: 'url',
                method: 'POST',
                success: function (form, action) {
                    
                },
                failure: function (form, action) {
                   
                },
                error: function (form, action) {
                  
                }
            });
        }
    },
    style:'margin-right:10px'
}

So In Change method How to get files details so I can write my handleFileSelect method.

Any idea willbe helpfull.

why the output file is empty?

I use the child_process to execute shell script the code as follow:

var timeAspCommand = "{ time clingo" + " " +programParam + " " + dataParam +" 2> clingo_sterr ; } 2> /root/output/output_clingo.txt"

let timeAspChildProcess = exec(timeAspCommand, function ( error, stdout, stderr){
          cb(null,stdout)
});

the output/stdout is :

clingo version 5.4.0
Reading from ...ngo/clingoProgram/borda_asp_program.lp ...
Solving...
Answer: 1
borda_win(2) borda_score(1,-286) borda_score(2,382) borda_score(3,88) borda_score(4,-292) borda_score(5,108)
SATISFIABLE

Models       : 1
Calls        : 1
Time         : 0.002s (Solving: 0.00s 1st Model: 0.00s Unsat: 0.00s)
CPU Time     : 0.002s

I expect the content of output_clingo.txt is :

real    0m0.005s
user    0m0.005s
sys 0m0.000s

however, when I imput the shell script cat /root/output/output_clingo.txt,there is nothing .

what should I solve this problem?

thanx!

What should i do?

react-dom.development.js:86 Warning: Invalid DOM property class. Did you mean className?
at h5
at div
at div
at div
at div
at div
at div
at ContactUs (http://localhost:3000/static/js/bundle.js:1525:84)
at div
at Home
at Routes (http://localhost:3000/static/js/bundle.js:89329:5)
at div
at App
at Router (http://localhost:3000/static/js/bundle.js:89262:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:88071:5)

405 Not Allowed nginx only without debugging

I developed an application with a login mask. In the login there is a request to an express backend on a server with nginx.

If I run this without debugging I get the 405 Not Allowed Error from nginx. I can avoid that by using #error_page 405 =200 $uri; but this does not solve my problem.

If I debug it in the browser and set a breakpoint at the .then()… position, it works.

Do you have any suggestion?
Thank you very much!

const login = () => {
    let email = document.getElementById("inputEmail").value;
    let password = document.getElementById("inputPassword").value;
    fetch(`${path}/auth/login`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            email: email,
            password: password,
        }),
    })
        .then(async (response) => {
            if (response.status === 400) {
                document.getElementById("errorContainer").style.display =
                    "inherit";
                document.getElementById("errorField").innerHTML = e.value;
            } else if (response.status === 200) {
                response.json().then((parsedJson) => {
                    try {
                        console.log(parsedJson);
                        localStorage.setItem(
                            "authToken",
                            parsedJson.data.user.token
                        );
                        window.location.href = `${path}/verkauf`;
                    } catch (e) {
                        window.location.href = `${path}/auth`;
                    }
                });
            } else {
                document.getElementById("errorContainer").style.display =
                    "inherit";
                document.getElementById("errorField").innerHTML = e.value;
            }
        })
        .catch((e) => {
            document.getElementById("errorContainer").style.display = "inherit";
            document.getElementById("errorField").innerHTML = "Fehler";
        });
};

NGINX

server {
    listen 80;

    server_name XXXXXX;
    
location /verkauf {
    alias /var/www/kioskJPE/html;
    index index.html;
}

location /admin {
    alias /var/www/kioskJPE/html;
    index admin.html;
}
location /authentication {
    #error_page 405 =200 $uri;
    alias /var/www/kioskJPE/html;
    index authentication.html;
}

location /auth/ {
        proxy_pass http://localhost:8000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }
location /kiosk/ {
       proxy_pass http://localhost:8000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }

}

Hot to map over array of arrays to filter out double entries

I want to map over this Array of Arrays. Those with multiple Objects have multiple entries in the same month (in the example below january). I want to filter out the double entries and want to return the filtered array.
I tried different solutions here on SO but failed so far, appreciate any input!

0: [{…}]
1: [{…}]
2: [{…}]
3: [{…}]
4: [{…}]
5: [{…}]
6: (2) [{…}, {…}]
7: (2) [{…}, {…}]
8: (2) [{…}, {…}]
9: (2) [{…}, {…}]
10: (2) [{…}, {…}]
11: (2) [{…}, {…}]
12: [{…}]
13: [{…}]
14: [{…}]
15: [{…}]
16: [{…}]
17: [{…}]
18: (2) [{…}, {…}]
19: (2) [{…}, {…}]
20: Array(2)
0: {id: '29', bookingReason: 'Netto Neu Eigen', bookingDate: '2022-01-22', bookingType: 'Gutschrift', bookingPoints: '100'}
1: {id: '30', bookingReason: 'Netto Neu Eigen', bookingDate: '2022-01-23', bookingType: 'Gutschrift', bookingPoints: '100'}
length: 2
[[Prototype]]: Array(0)
21: Array(2)
0: {id: '29', bookingReason: 'Netto Neu Eigen', bookingDate: '2022-01-22', bookingType: 'Gutschrift', bookingPoints: '100'}
1: {id: '30', bookingReason: 'Netto Neu Eigen', bookingDate: '2022-01-23', bookingType: 'Gutschrift', bookingPoints: '100'}
length: 2
[[Prototype]]: Array(0)
22: (2) [{…}, {…}]
23: (2) [{…}, {…}]

Is it lecit to pass an event emitter to a function?

Suppose I have this example:

function transform(data) {
  const out = new EventEmitter();
  async function run() {
    try {
      const url = await initialise();
      const data = await downloadFile(url);
      out.emit('data', data);
    } catch(err) {
      out.emit('error', err);
    }
  }

  async function initialise() {
    const req = superagent.post('url...')
    superagent.send(data)
    const res = await req // this will actually fire the request
    out.emit('initialize')
    return res.body
  }

  async function downloadFile(url) {
    const req = superagent.put(url)
    req.on('progress', (progress) => out.emit('downloadFile', progress)
    const res = await req; // this will actually fire the request
    //
    // save to disk
    //
    return data;
  }

  run();
  return out;
}

(https://stackoverflow.com/a/48794504/3154403)

Then, suppose I would like to have another function stuff() that will be called by downloadFile(). stuff() would do some things I would like to notify.

What’s the best option?

  1. Pass the emitter to stuff()
async function stuff(emitter) {
    let var
    var = await task1()
    emitter.emit('task1', var)
    var = await task2()
    emitter.emit('task2', var)
    var = await task3()
    emitter.emit('task3', var)
    return var
}
  1. or have stuff() returning a new emitter and listening on it?
  async function downloadFile(url) {
    const req = superagent.put(url)
    req.on('progress', (progress) => out.emit('downloadFile', progress)
    const res = await req; // this will actually fire the request
    
    stuff().on('task1', var => out.emit('task1', var)
    // eventual other listeners

    return data;
  }