Mock promise that never resolves with Jest

With jest, is there a way to mock a promise that never resolves? I want to write a snapshot test where I verify my UI in a loading state. The loading state depends on a promise. If the promise resolves, the loading state goes away.

Template:

<div v-if="isLoading">
  <div>Starting service, please wait</div>
</div>

Script:

async startService() {
    try {
      this.isLoading = true;
      const response = await this.service.start();
      this.isLoading = false;
    }

Proposed test:

it('loading screen should display', async() => {
  const startServiceSpy = jest
    .spyOn(Service.prototype, 'start')
    .mockImplementation(() =>
      DO NOT RESOLVE SERVICE CALL HERE
    }));

  await wrapper.vm.startService();

  // show loading screen in snapshot
  expect(wrapper.html()).toMatchSnapshot();

});

Swagger UI require fails in Node.js application

I have a Node.js application using Electron v15.3.1. I embed a Swagger UI for viewing OAS files. The Swagger UI version I am using is 4.6.1. It now has a security vulnerability so I need to upgrade it.

I first tried to run npm audit fix which ran successfully, but after that the Swagger UI fails at time when i require it:

let SwaggerUI = require('swagger-ui')

With this error printed in the console of Chrome Dev Tools:

VM67 node:vm:108 Uncaught /Users/benjaminmogensen/workspace/API-JSON-Schema-Definitions/node_modules/react-syntax-highlighter/dist/esm/light.js:1
(function (exports, require, module, __filename, __dirname, process, global, Buffer) { return function (exports, require, module, __filename, __dirname) { import highlight from './highlight';
                                                                                                                                                           ^^^^^^

SyntaxError: Cannot use import statement outside a module
    at new Script (node:vm:100:7)
    at createScript (node:vm:257:10)
    at Object.runInThisContext (node:vm:305:10)
    at wrapSafe (node:internal/modules/cjs/loader:1021:15)
    at Module._compile (node:internal/modules/cjs/loader:1066:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1140:10)
    at Module.load (node:internal/modules/cjs/loader:982:32)
    at Module._load (node:internal/modules/cjs/loader:823:12)
    at Function.c._load (node:electron/js2c/asar_bundle:5:13331)
    at Function.o._load (node:electron/js2c/renderer_init:29:379)

Next, I tried to upgrade to latest version 4.9.0, instead of running npm audit fix. After updating the package.json file and running npm install it’s the same result.

I then tried all other versions from 4.6.1 up to 4.9.0 and its the same result. I then tried a previous version – same result.

I have also tried to do a npm cache verify.

However, when I revert to version 4.6.1 and do npm install it works again.

Any help, very much appreciated!

Vue3 Directives

I’m getting my feet wet with Laravel in combination with Vue3.

Theres something I can’t really figure out, as every example I found does not seem to do anything at all.

I want to add a custom directive to my component.

This is what I have so far:

<template>
    <div class="ml-3 relative">
        <div>
            <button @click="toggleShowUserMenu" type="button" class="bg-gray-800 p-1 text-gray-400 rounded-full hover:text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white" aria-expanded="false" aria-haspopup="true">
                <span class="sr-only">Open user menu</span>
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
            </button>
        </div>
        <div :class="{hidden: showMenu}" class="origin-top-right absolute right-0 mt-2 w-48 rounded-md shadow-lg py-1 bg-white ring-1 ring-black ring-opacity-5 focus:outline-none" role="menu" aria-orientation="vertical" aria-labelledby="user-menu-button" tabindex="-1">
            <a @click="logout" v-click-outside="outside" class="block px-4 py-2 text-sm text-gray-700 cursor-pointer hover:bg-gray-200" role="menuitem" tabindex="-1">Sign out</a>
        </div>
    </div>
</template>

<script>
const clickOutside = {
    beforeMount: (el, binding) => {
        el.clickOutsideEvent = event => {
            if (!(el === event.target || el.contains(event.target))) {
                binding.value();
            }
        };
        document.addEventListener("click", el.clickOutsideEvent);
    },
    unmounted: el => {
        document.removeEventListener("click", el.clickOutsideEvent);
    },
};

export default {
    props: {
        logoutUrl: { type: String, required: true }
    },
    directives: {
        clickOutside
    },
    methods: {
        toggleShowUserMenu() {
            this.showMenu = !this.showMenu;
        },
        logout() {
            axios.post(this.logoutUrl)
                .then(() => window.location = '/')
                .catch(() => console.error('Logout failed'));
        },
        outside() {
            console.log('OUTSIDE');
        }
    },
    data() {
        return {
            showMenu: true
        }
    }
}
</script>

But this isn’t working and I don’t know why. One thing I notice is that the app I have is being initialized differently from the docs (this is scaffolded by Laravel)

I have this in my app.js.

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue').default;

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('user-menu', require('./components/UserMenu').default);
Vue.component('integration-status-list', require('./components/IntegrationStatusList').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
});

But looking at the vue docs I see initialization of a vue app is quite different, like this:

import { createApp } from 'vue'

const app = createApp({
  /* root component options */
})

I also tried to register the directive globally, by adding app.directive('clickOutside', clickOutside); to app. But still, no luck at all. Nothing is happening, it’s not even initializing. I wondere what I’m missing here.

Rotate Tetris Piece JS

I’m working on a Tetris Challenge and dealing with a problem when rotating the piece.

Basically I have a two-dimensional array and using a for loop I’m exchanging the items in this position array, the problem is that the movement is not centered in the middle of the piece.

See a representation of the array before and after the spin:

original — after
0 1 0 0 — 0 0 0 0
1 1 1 0 — 0 1 0 0
0 0 0 0 — 1 1 0 0
0 0 0 0 — 0 1 0 0

function rotate( piece ) {
    var newPiece = [];
    for ( var y = 0; y < 4; y++ ) {
        newPiece[ y ] = [];
        for ( var x = 0; x < 4; x++ ) {
            newPiece[ y ][ x ] = piece[ 3 - x ][ y ];
        }
    }

    return newPiece;
}

Any insights that might help me with this?
Thanks!!

Trying to get property ‘user’ of non-object. i get this error when i load this page

Here is the code. Please help. thanks

"use strict";

load_data();

function load_data(status = '',requests='') {
  var table = $('#maintable').DataTable({
    processing : true,
    serverSide : true,
    ajax : {
      url : $('#maintable').attr('data-url'),
      data : {status : status, requested : requests}
    },
    columns : [
      {data : 'id', name : 'id'},
      {data : 'image', name : 'image'},
      {data : 'visitor_id', name : 'visitor_id'},
      {data : 'name', name : 'name'},
      {data : 'employee_id', name : 'employee_id'},
    
      {data : 'date', name : 'date'},
      {data : 'checkout', name : 'checkout'},
      {data : 'status', name : 'status'},
      {data : 'action', name : 'action'},
    ],
    "ordering" : false
  });

  let hidecolumn = $('#maintable').data('hidecolumn');
  if(!hidecolumn) {
      table.column( 5 ).visible( false );
  }
}

$('#maintable').on('draw.dt', function () {
  $('[data-toggle="tooltip"]').tooltip();
})

This is i what i get whenever i load this page and it refuses to load the needed data to the table. Please what is wrong? Waiting for your solutions…thanks

Outer function argument not displayed when debugging inner function in chrome

I have function like:

const outer = payload => dispatch => {
   debugger;
return 0;
}

chrome devtools screenshot

Should I see payload variable when debugging it in chrome devtools? I was looking for it in closures as you can see in the screenshot. There is no payload there or I cannot find it. However when I change the code to:

const outer = payload => dispatch => {
   console.log({ payload });
   debugger;
return 0;
}

I can see payload variable appearing under one of the closure boxes on the right side when debugging.

I think I don’t fully understand the behaviour of closures(?) Could you please tell me in short how these two codes work behind the scenes?

Why are the div’s not included in the dark-mode function?

I’m new to this language. So far I’ve only dealt with html and css. Thats why i looked up a Totourial. I took the code and tried to change it. It worked for the beginning, but when I tried to add divs in dark mode, it didn’t work.
So my problem is that the divs are not included in the dark mode, and the font, font-color etc. I thought by adding div instead of body, it would work. But this was not the case…
I hope you can help me with that.

<div class="power">

     <div id="toggle">

        <i class="indicator"></i>

     </div>

      <script>

      const body = document.querySelector('body');
      const div = document.querySelector('div');
      const toggle = document.getElementById('toggle');
            toggle.onclick = function(){
                   toggle.classList.toggle('active');
                   body.classList.toggle('active');
                   div.classList.toggle('active')

                                }

                    
     </script>
                           
</div>

CSS: 

body {

    background-image: radial-gradient(#ada9a9 2%, transparent 7%),
    radial-gradient(#928f8f 2%, transparent 7%);
    background-color: #f8efd6;
    background-position: 25px 35px, 50px 50px;
    background-size: 20px 20px;
    transition: 0.5s;
    
}



body.active{

    
    background-image: radial-gradient(#5c5252 2%, transparent 7%),
        radial-gradient(#928f8f 2%, transparent 7%);
    background-color: #16140f;
    background-position: 25px  35px, 50px 50px;
    background-size: 20px 20px;

}


#toggle {

    position: relative;
    display: block;
    width: 100%;
    height: 40px;
    border-radius: 160px;
    background: #fff;
    transition: 0.5s;
    cursor: pointer;
    box-shadow: inset 0 2px 60px rgba(0,0,0,0.1),
                inset 0 2px 8px rgba(0,0,0,0.1),
                inset 0 -4px 4px rgba(0,0,0,0.05);

}

#toggle.active {

    background-color: #222;
    box-shadow: inset 0 8px 60px rgba(0,0,0,0.1),
                inset 0 8px 8px rgb(0,0,0,0.1),
                inset 0 -4px 4px rgb(0,0,0,0.1);


}

#toggle .indicator {

    position: absolute;
    top: 0;
    left: 0;
    width: 40%;
    height: 40px;
    background: linear-gradient(to bottom, #eaeaea,#f9f9f9);
    border-radius: 50%;
    transform: scale(0.9);
    box-shadow: 0 8px 40px rgba(0,0,0,0.5),
                inset 0 4px 4px rgba(255,255,255,1),
                inset 0 -4px 4px rgba(255,255,255,1);
    transition: 0.5s;


}

#toggle.active .indicator {

    left: 60%;
    background: linear-gradient(to bottom, #444,#222);
    box-shadow: 0 8px 40px rgba(0,0,0,0.5),
                inset 0 4px 4px rgba(255,255,255,0.2),
                inset 0 -4px 4px rgba(255,255,255,0.2);
    transition: 0.5s;

}

div.active {

    background-color: rgb(31, 31, 31);

}

React-select on change not triggered inside bootstrap dropdown

I am very puzzled by this and probably missing something really stupid. I have to selects inside a bootstrap dropdown, one is generic select and other is a react-select component. When I use the generic select and change the selected value, the onChange get triggered and works perfectly. When I change the value of the react-select, nothing happens at all. If I take it out of the dropdown, it does trigger as it should….

Any pointers on how to solve would be greqatly appreciated!


import React from 'react'
import Select from 'react-select'

export function Filter({ headerGroups }: { headerGroups: any }) {
    return (
        <>
            <button
                type="button"
                className="input-group-addon btn input-sm dropdown-toggle icon-filter"
                data-toggle="dropdown"
            />
            <ul
                id="dropdown-toggle"
                className="dropdown-menu pull-right dropdown-menu"
                data-autoclose="false"
            >
                <li>
                    {headerGroups.map((headerGroup) =>
                        headerGroup.headers.map((column) =>
                            column.canFilter ? (
                                <fieldset
                                    key={column.id}
                                    style={{ float: 'left' }}
                                >
                                    <legend>{column.Header}</legend>
                                    <Select
                                        key={column.id + Math.random()}
                                        id={column.id}
                                        isSearchable
                                        options={options}
                                        value={column.filterValue}
                                        closeMenuOnSelect
                                        onChange={(e) => handleChange(e)}
                                    />
                                    <select
                                        key={column.id + 'gjwi'}
                                        id={column.id}
                                        value={column.filterValue}
                                        onChange={(e) => handleChange(e)}
                                    >
                                        {options.map((option) => {
                                            return (
                                                <option
                                                    key={
                                                        option.value +
                                                        Math.random()
                                                    }
                                                    value={option.value}
                                                >
                                                    {option.label}
                                                </option>
                                            )
                                        })}
                                    </select>
                                </fieldset>
                            ) : null
                        )
                    )}
                </li>
            </ul>
        </>
    )
}

The “module” configuration of TS config does not work?

index.ts

const m = require("./test");
console.log(m.a);

test.ts

module.exports = {
  a: 1,
  b: 2,
};

After compilation

index.js

var m = require("./test");
console.log(m.a);

test.js

module.exports = {
    a: 1,
    b: 2
};

The module specified in tsconfig.json is ES6. It should be compiled into a modular way such as import {a} from 'test'. Why is it still the modular way of commonjs?
enter image description here

How to override a prop component used as props in the returned component

I’m coding a component to facility the use of material-ui React Autocomplete component, It new component has a few props then return the React Autocomplete component with its own props assigned, how Can I override the React Autocomplete prop “onChange” in some situations where I need to add additional code lines?

import React from 'react';
import './CustomAutocomplete.css';
import { Autocomplete, createFilterOptions } from '@material-ui/lab';
import { TextField } from '@material-ui/core';

interface CustomAutocompleteProps {
  placeholder: string;
  options: any[];
  optionSelected: any;
  setOptionSelected: (newValue: any) => void;
  startSearchLength: number;
  optionsSuggestionLimit: number;
}

export const CustomAutocomplete = (props: CustomAutocompleteProps) => {
  const defaultFilterOptions = createFilterOptions();
  const filterOptions = (options, state) => {
    return defaultFilterOptions(options, state).slice(
      0,
      props.optionsSuggestionLimit
    );
  };

  return (
    <Autocomplete
      placeholder={props.placeholder}
      filterOptions={filterOptions}
      value={
        props.options.length === 1 ? props.options[0] : props.optionSelected
      }
      options={props.options ? props.options : []}
      disabled={props.options.length === 1}
      getOptionSelected={(option, value) => option.name === value.name}
      getOptionLabel={(option) => option.name || ''}
      onChange={(event: any, newValue: any) => {
        props.setOptionSelected(newValue);
      }}
      renderInput={(params) => (
        <TextField
          {...params}
          variant="standard"
          placeholder={props.placeholder}
          onChange={(event: any) => {
            event.target.value.length > props.optionsSuggestionLimit &&
              props.setOptionSelected(event.target.value);
          }}
        />
      )}
    />
  );
};

In some cases I need to add more set useState in onChange props but if I add it in the CustomAutocomplete component it will attempt to execute in every import. How can I overried and called just in a specific situation?

onChange={(event: any, newValue: any) => {
        setOptionSelected(newValue);
setoptionSelected2(newValue);
setOptionSelected3(newValue);
      }}

Do you have any idea? Thanks!

Shuffle a container’s DOM elements but not all in javascript

Trying to shuffle a container’s (a div) DOM elements (other divs) with a particular class name (“div”). Other divs (“extra”) should stay put in the place where they are.

So far I have used the modified shuffle algorithm from link

The code I have almost did the trick but the “Extra” div is appended at the bottom of the stack while it’s supposed to stay atop.

HTML I have:

<div class="divver">

<div class="extra">
Extra
</div>

<div class="div">
1
</div>
<div class="div">
2
</div>
<div class="div">
3
</div>
<div class="div">
4
</div>
<div class="div">
5
</div>
</div>

<button onclick="shuffler()" id="shuffles">
Shuffle 'em
</button>

JS:

let divs = document.getElementsByClassName("div")
let divsNumber = divs.length;
let divver = document.getElementsByClassName("divver")[0]

function shuffler() {
for (var i = divsNumber; i >= 0; i--) {
    if(!divver.children[i].classList.contains("div")) {
    divver.appendChild(divver.children[Math.random() * i | 0]);
}
}
}

JSFiddle

Any hints greatly appreciated.

setInterval vs clearInterval which is better to run a loop at a specified speed

var speed = 200,
  len = 0;
if (e in know) {
  function typing() {
    if (len < know[e].length) {
      if (len === know[e].length - 1) {
        t.innerHTML = know[e];
        g = d.getAttribute("data-bottom") ? d.getAttribute("data-bottom") : 0;
        if (parseInt(g) < ((d.scrollHeight - t.offsetTop) - p.clientHeight) + 10) d.scrollTo(0, d.scrollHeight);
        else alert("new message");
      }
      len++;
      setTimeout(typing, speed);
    }
  }
  typing();

setTimeout vs
setInterval code…

var setIn = setInterval(() => {
  if (len < know[e].length) {
    if (len === know[e].length - 1) {
      clearInterval(setIn);
      t.innerHTML = know[e];
      g = d.getAttribute("data-bottom") ? d.getAttribute("data-bottom") : 0;
      if (parseInt(g) < ((d.scrollHeight - t.offsetTop) - p.clientHeight) + 10) d.scrollTo(0, d.scrollHeight);
      else alert("new message");
    }
    len++;
  }
}, speed)

I’m trying to make a reply bot that starts typing after 1 seconds and that will reply back at the speed of the String.length and they both did the same thing but someone once told me using setTimeout is bad practice, but I need them to run that exact way. If there is another work around for it I’m open to all suggestions, Thanks in advance.

How to detect if point is inside a natural area (or other type) polygon with overpass?

I am trying to figure out how to detect if latitude/longitude pair (-25.70078,-54.44522) is inside a natural area polygon.

Is there a better solution ?

So far I have something like this:
https://overpass-turbo.eu/s/1h8D

This code gets me the nearest area but it also gets me the closest areas, which I don’t want.

I need to know if the point is “in” (true) the specified area.