Calling jest.clearAllMocks() in beforeEach clears calls within a test?

I’m seeing an issue in Jest where calling jest.clearAllMocks() inside a beforeEach callback seems to wipe out calls to a mocked function that are made not before but WITHIN a specific test. I can repro it as follows:

THIS PASSES:

__tests__/testy.test.js

const AWS = require("aws-sdk");
const { handler } = require("../index.js");

describe("Lambda function tests", () => {
    it("sent the expected CSV data to S3", async () => {
        // RUN THE LAMBDA, await completion
        await handler();
        // The S3 constructor should have been called during Lambda execution
        expect(AWS.S3).toHaveBeenCalled();
    });
});

THIS GIVES ME A FAILURE:

__tests__/testy.test.js

const AWS = require("aws-sdk");
const { handler } = require("../index.js");

describe("Lambda function tests", () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });
    it("sent the expected CSV data to S3", async () => {
        // RUN THE LAMBDA, await completion
        await handler();
        // The S3 constructor should have been called during Lambda execution
        expect(AWS.S3).toHaveBeenCalled();
    });
});

The failure message in the console:

expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

I’m using jest version 27.4.3 in Node v14.18.1. In case it matters, I’m mocking aws-sdk like this:

__mocks__/aws-sdk.js

const AWS = jest.createMockFromModule("aws-sdk");

AWS.S3 = jest.fn().mockImplementation(() => ({
    upload: jest.fn(() => ({ promise: jest.fn() })),
    headObject: jest.fn(() => ({
        promise: jest.fn(() => ({ ContentLength: 123 })),
    })),
}));

module.exports = AWS;

What could be happening here?

How to render a list of array items depending on the selected calendar item in a Vue project?

Here’s the calendar I’m talking about:

CalendarApp

So, basically, I’ve tried to create a following feature: Each day item contains an empty array which will then contain the N number of tasks that are added to that empty array by the purple button below depending on which day is active (The highlighted one), so each day item will have its own array of tasks and I can switch between them to see how many tasks on which day are created. I use Vuex and Vue3 Composition API for this project.

Calendar component:

Calendar.vue

<template>
<div class="wrapper">
  <div class="calendar-wrapper">
      <div class="calendar-row"
           v-for="(day, idx) in dayArr"
           :key="idx"
        >
          <div
            id="card"
            class="day-card "
            :class="{ 'active' : activeDay === idx + 1 }"
            @click="switchDay(idx)"
          > 
              <div class="card-info">
                <p class="name">{{ day.dayOfWeek }}</p>
                <p class="day">
                    {{ day.currDay }} 
                </p>
              </div>
             <div class="dot-wrapper">
                <div class="dot-status undone" />
                <div class="dot-status undone" />
             </div>
          </div>

      </div>
  </div>
</div>
</template>

<script>
/* eslint-disable no-unused-vars */
import { useStore } from 'vuex'
import { onMounted, ref } from 'vue'

export default {
  
  /*=============================================
  =            Setup            =
  =============================================*/
    setup() {
    // ? Turn the remaining days into an array 
    const fillDayArray = () => {
      dayArr.value = Array(daysRemainingThisMonth)
        .fill('')
        .map((item, index) => {
          return {
            currDay: moment().add(index, 'day').format('D'),
            dayOfWeek: moment().add(index, 'day').format('dddd'),

            // Empty array for added tasks:
            tasks: []
  
          };

      })

      }
     // Make the clicked day active
    const switchDay = (idx) =>  {
      activeDay.value = idx + 1
    }

    onMounted(() => {
      fillDayArray() 
      
    })

</script>

Area where tasks are rendered and created:

TaskView.vue

<template>
    <div class="task-wrapper">
        <p id="task-counter">
            Tasks Today: {{ taskArr.length }}
        </p>
        <div class="task-counter-wrapper">                 
            <!-- ? Render if there are no tasks available: -->
            <div 
                class="empty-msg"
                v-if="taskArr.length == 0"
            >
                <p>Start by adding a New Task!</p>
            </div>

            <div 
                class="task-list" 
                v-for="(task, idx) in taskArr"
                :key="idx"
            >
                <div class="list-item">
                    <div class="container">
                        <input class="list-checkbox" type="checkbox">
                        ({{ idx + 1}}) {{ task.name }}
                    </div>

                    <div class="item-actions">
                        <button 
                            class="edit-item btn"
                            @click="getClickedTask(task)"
                        > 
                            <img class="icon" src="./Images/editing.png">
                        </button>

                        <button 
                            class="delete-item btn"
                            @click="deleteItem(idx)"
                        >
                            <img class="icon" src="./Images/delete.png">
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="item-card">
            <ItemCard />
        </div>  

        <div class="add-task-wrapper">
            <button 
                id="add-task-btn"
                @click="addItem()"
            >
                + Add a new task
            </button>
        </div>
    
    </div>
</template>

<script>
/* eslint-disable vue/no-unused-components */
import ItemCard from './ItemCard.vue'
import { useStore } from 'vuex'
// import { computed } from '@vue/reactivity'

export default {
    components: {
        ItemCard
    },

    setup() {
        const store = useStore()
        const taskArr = store.state.taskArr
    
    
        const getClickedTask = (item) => {
            store.state.clickedTask = item
            
            store.state.cardStatus ?
                store.state.cardStatus = false 
                :
                store.state.cardStatus = true
        };

        // ! Delete Item:
        const deleteItem = (idx) => {
            store.state.taskArr.splice(idx, 1)
        }

        const addItem = () => {
            store.state.taskArr.push(
                {
                    name: 'Empty Task' + Math.random().toString().substring(0, 4), 
                    description: 'No description...' 
                }
            )
        }
            
    },

}
</script>

Main area where all other component are rendered:

Main.vue

<template>
 <div id="main">
     <!-- ! Top Level: -->
    <div class="auth">
        
    </div>
    
    <div class="greeting-block">
         <button @click="signOutUser">Sign Out</button>
         <h1 id="greet-user"> {{ user?.email }}</h1>
    </div>

     <div class="header-container">
         <Header />
         <Menu />
         
     </div>

    <div class="calendar-display">
        <Calendar />
    </div>

 
    <div class="task-list">
        <TaskView />
    </div>

 </div>
</template>

<script>
/* eslint-disable vue/no-unused-components */
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
// ? UI Components:
import Header from './Header.vue';
import Calendar from './Calendar.vue';
import Menu from './Menu.vue';
import TaskView from './TaskView.vue';
// ? Auth components:
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Auth from '../Auth.vue'
// ? Firebase:
import { getAuth } from '@firebase/auth'
import { signOut } from '@firebase/auth'
import { useAuthState } from '../firebase'
// ? Router:
import { useRouter } from 'vue-router'
// ? Store: 
import { useStore } from 'vuex'
// ? ref():
import { ref } from 'vue'


export default {
    components: {
        Header,
        Calendar,
        Menu,
        TaskView,
        Login,
        Register,
        Auth
    },
     name: 'Home',

    setup() {
        /*=============================================
        =            Firebase            =
        =============================================*/
        const { user } = useAuthState()
        const auth = getAuth()  

        const router = useRouter()
        const signOutUser = async () => {
            try {
                await signOut(auth)
                router.push('/auth')
            
            } catch(e) {
                alert(e.message)
            }
        }
        /*=====  End of Firebase  ======*/
        const store = useStore()


        const taskArr = store.state.taskArr
        
    }
}
</script>

Vuex store

index.js

state: () => {
    return {
      cardStatus: false,

      clickedTask: null,
      taskStatus: null,

      dayIsActive: 'active',

      cardVisible: true,
      // The desired array
      taskArr: [ ]
    }
  },

I think that I probably need to use props, but I really have no idea how do I implement this here. Any ideas would be very appreciated!

Javascript: Creating and Calling Dynamic Variables? [duplicate]

I have a script that contains 3 questions. I have started by creating 3 variables (ex: var q1 = “question here”) and I have a function that randomly picks a number between 1 and 3 and chooses that question (var question = “q” + rand;) but if I want to reference this variable called question to output the question in HTML (ex: document.getElement.Id(“output”).innerHTML += question;) how would I do so?

Here is my code:

// Questions List
        var q1 = " Question 1 here"
        var q2 = "Question 2 here"
        var q3 = "Question 3 here"

  // Randomly generate a question and then output it
        var randy = Math.floor(Math.random()*3+1);
        var question = "q" + randy;
        document.getElementById("output").innerHTML += question;
        
    
<!doctype html>
<html>
<body>
  <div id="output"></div>
</body>
</html>

So basically the script will choose a question from 1 to 20 and output it to my HTML div tag.

Sorry if this isn’t clear. Any help is greatly appreciated.

React Native encrypt a message with publicKey. Convert encrypted to base64

I need to do, for react native, encryption of a message.
I tried several libraries, but none worked.
(
JSEncrypt (not supported)
NODERSA (didn’t work)
expo-crypto (I couldn’t set the public key because I have my key)
react-native-rsa (it didn’t work either because of the key)
)

I wonder if anyone knows a way to do this!?


I have the public key and the message.
I need to encrypt the message with the public key and pass it to base64.

Multiple Calls to Custom Hook not yielding expected result

I am having a hard time understanding why the onClick event handler (which invokes 2 calls to a custom hook wrapper function) is not responding properly. I expect that everytime I click the button in the example would swap its border color from green to red based on a value that is being incremented. I understand the example is rudimentary and could easily be solved by conditioning the error prop on the value.value instead of sharing , but this is a simplified example of a more complex interaction, and I have boiled down the issue to a simple example for clarification. Any help would be appreciated.
https://codesandbox.io/s/custom-hooks-with-closure-issue-2fc6g?file=/index.js

Why does my tab don’t change when clicking the button?

I’m developing a new website, with a multi-step form where the steps are all in separated divs. The problem is: when i click in the first button, it shows the second page, but then it goes back to the first.
Here’s my javascript code:

<script>
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab

function showTab(n) {
  // This function will display the specified tab of the form ...
  var x = document.getElementsByClassName("tab");
  x[n].style.display = "block";
}

function next(n) {
  // This function will figure out which tab to display
  var x = document.getElementsByClassName("tab"); 
  // Hide the current tab:
  x[currentTab].style.display = "none";
  // Increase or decrease the current tab by 1:
  currentTab = currentTab + n;
  // if you have reached the end of the form... :
  if (currentTab >= x.length) {
    //...the form gets submitted:
    document.getElementById("regForm").submit();
    return false;
  }
  // Otherwise, display the correct tab:
  showTab(currentTab);

}

</script>

My html/php code for first two divs:

 <div class="tab">
    <div id="layout">
        <div class="main">
            <div class="logo">
                <img src="pictures/propcomp.png"/>
            </div>   
            <div class="text">
                <h3 class="blue">Olá!</h3> <br>
                <h3 class="grey">Seja bem vindo(a) à empresa número 1 na pesquisa Google nesse modelo de férias. Bem como já temos mais de 11.300 inscritos no nosso canal no YouTube.</h3>
                <h3 class="blue"><strong>Parabéns!</strong></h3>
                <h3 class="blue normal"><strong class="negrito">Você foi pré-selecionado pelos nossos Analistas de Férias de Alto Padrão </strong> para
                    participar de uma consultoria <strong class="negrito">gratuita e exclusiva</strong> de férias onde na mesma você
                    conhecerá um método de viajar mais e melhor com sua família. Contudo o seu
                    tempo para gente vale ouro, então vamos te presentear com um brinde para que
                    você participe da consultoria. Leia até o final se você quiser saber qual é o brinde!</h3> <br>
            </div>
            <div class="home">
                <a href="">
                <button class="btn btn-beleza" type="button" id="nextBtn" onclick="next(1)">
                 <label class="beleza">Beleza! Quero Participar!</label> 
                <img src="pictures/arrow.svg" />
                </button>
            </a>
            <div class="beneficio">
                <a href="" style="display: flex;"><img src="pictures/interrogacao.svg"/><h4 class="blue normal">Por que estou recebendo esse benefício?</h4></a> 
                
       </div>
            </div>
            <div class="footerimg">
                                 <img style="width:30px; height: 44.5px;"src="pictures/logopequeno.png"/>
                </div>
        </div>
    </div>
</div>

<div class="tab">
<div class="layout">
        <div class="main">
            <div class="text">
                <div class="uausorriso">
                    <h3 class="blue negrito">Uauuuuuuuu, você é demais!!</h3> 
                    <img src="pictures/sorriso.png"/>
                </div>
                <h3 class="grey normal">Te parabenizamos por priorizar suas férias e novas experiências. Aliás, tudo passa e o
                    que fica são os momentos que vivemos com as pessoas que amamos. Afinal, qual é
                    a história que você vai contar?</h3>
                <h3 class="blue normal">Para começar, qual é o seu nome?</h3>
            </div>
            <div class="">
              
                    <input class="inputfield" style="margin-left:32%;"type="text" id="nome" name="nome"><br>
                   
                    <div class="avancar">
                    <a href="">
                    <button class="btn" type="button" id="nextBtn" onclick="next(1)">
                     <h3>Avançar</h3> 
                    <img src="pictures/arrow.svg" />
                    </button>
                </a>
                </div> 
        </div>
    </div>
</div>

I’ve put this online so you can see visually: https://testedeferias.000webhostapp.com/

Vue get params from url & path to app in subfolder of laravel

i used Vue 2.6 for little App with flipbook-vue, and i mounted it in subfolder of my Laravel APP in public/dist/.

I need to get params from url, and i do it like that:

Router index.js:

export default new Router({
  mode: 'history',
  routes: [{ path: "/:numer", component: Newspaper }]
})

vue.config.js:

module.exports = {
  publicPath: '/gazetka/',
}

And in Vue component i use $route.params to get this params.
The problem is that Vue reads the subfodler name dist to me as a parameter.
How do I get around it?
I tried .htaccess but it doesn’t work locally.

Using jQuery UI to open and close search box?

I’m setting up an autocomplete search box.

Here’s my current code:

$(document).ready(function(){
 
 $('#txtSearch').autocomplete({
     source: "https://example.com/search.php",
     minLength: 1,
     select: function(event, ui) {
         var url = ui.item.id;
         if (url != '#') {
             location.href = 'https://' + location.hostname + '/' + url
         }
     },
     open: function(event, ui) {
         $(".ui-autocomplete").css("z-index", 1000)
         $('.exo-search').css('border-bottom-left-radius','0');
         $('.exo-search').css('border-bottom-right-radius','0');
     }
 })
 
});

You can see here that someone starts typing and the results are loading, it sets the bottom border radius to 0.

 open: function(event, ui) {
     $(".ui-autocomplete").css("z-index", 1000)
     $('.exo-search').css('border-bottom-left-radius','0');
     $('.exo-search').css('border-bottom-right-radius','0');
 }

But if someone clicks away from the search box, the dropdown of results disappears like it’s supposed to, but the bottom border radius is still set to 0 instead of resetting back to 5px like it normally is.

Is there something wrong with my code or is that the normal behavior and I need to add something else?

How to put in checkboxes values into a session variable without any button clicks?

lets say i have a code pretty similar like this

<form>
  <input type="checkbox" name="account1" value="1">
  <input type="checkbox" name="account2" value="2">
  <input type="checkbox" name="account3" value="3">
  <input type="checkbox" name="account4" value="4">


  <button type="submit">Delete</button>
</form>

Now i want to store the value of the checkbox in a php session once the user checked the boxes without clicking the submit/delete button. I plan to use jquery/ajax for this but i still cant quite wrap my head around it since im very new to ajax or jquery.

To add more detail, the process is like this..
the user can select any account he wants he checked. lets say he checked an account on page 1. he then went to another page(pagination) and then went back to page 1, the checked boxes would still be checked.

how to read aws cpu usage using node?

i want to build a small app that reads the AWS CPU USAGE every 5 minutes lets say, i built the params, call the getMetricsStatistics but it keeps returning me an empty array, you know why? this is the code:

const aws = require('aws-sdk')
const dotenv = require('dotenv').config()

aws.config.setPromisesDependency()
aws.config.update({
  accessKeyId: process.env.EC2_ACCESS_KEY,
  secretAccessKey: process.env.EC2_SECRET_KEY,
  region: 'us-east-1',
})
const s3 = new aws.CloudWatch()

var params = {
  EndTime: new Date() /* required */,
  /* required */
  MetricName: 'EngineCPUUtilization',
  Namespace: 'AWS/S3',
  StartTime: new Date('Mon Dec 6 2021') /* required */,
  /* required */
  Dimensions: [
    {
      Name: 'Per-Instance Metrics' /* required */,
      Value: 'i-abbc12a7' /* required */,
    },
    {
      Name: 'StorageType',
      Value: 'AllStorageTypes',
    },
    /* more items */
  ],

  Period: 300 /* required */,
  Statistics: ['Average'] /* required */,
}
async function asyncMethod() {
  return await s3.getMetricStatistics(params, function (err, data) {
    if (err) console.log(err, err.stack)
    // an error occurred
    else {
      console.log(data)
    }
  }) // successful response
}

const d = asyncMethod()

response is always empty array in the data.Datapoints.

understanding this when adding new object’s properties/methods (Javascript) [duplicate]

I’m a newbie trying to understand the value of this, when adding a new property and a new method.
Adding new property:

const Person = function (fname, lname) {
    this.fname = fname;
    this.lname = lname;
};
const bob = new Person('Bob', 'Sinclair');
bob.fullName = `${this.fname} ${this.lname}`  

in this example,
this will refer to the global object, therefore the value of fullName will be undefined. I get it.

Adding new method:

bob.printFirstName = function () {
    console.log(this.fname);
}  

now, why is this equal to the object? why, since is a function, is not equal to the global object or undefined (depending we are in non-strict/strict mode), Because is it a method? therefore the this in a method is equal to the object? I don’t get it.