NestJS test for password comparison should be passing

So I am working on a test for password comparison and the salted and hashed password for signing up should match the password for signing in.

The error in terminal is:

FAIL src/users/auth.service.spec.ts AuthService
✓ can create an instance of auth service (17 ms)
✓ creates a new user with a salted and hashed password (58 ms)
✓ throws an error if user signs up with email that is in use (2 ms)
✓ throws if sign in is called with an unused email (2 ms)
✓ throws if sign in is called with an unused email (49 ms)
✕ returns a user if correct password is provided (48 ms)

● AuthService › returns a user if correct password is provided

NotFoundException: user not found

  41 |     const [user] = await this.usersService.find(email);
  42 |     if (!user) {
> 43 |       throw new NotFoundException('user not found');
     |             ^
  44 |     }
  45 |
  46 |     const [salt, storedHash] = user.password.split('.');

  at AuthService.signin (users/auth.service.ts:43:13)
  at Object.<anonymous> (users/auth.service.spec.ts:83:18)

I console logged that user that is signing up in memory so the user is there.

describe('AuthService', () => {
  let service: AuthService;
  let fakeUsersService: Partial<UsersService>;

  beforeEach(async () => {
    // Create a fake copy of the UsersService
    const users: User[] = [];
    fakeUsersService = {
      find: (email: string) => {
        const filteredUsers = users.filter((user) => user.email === email);
        return Promise.resolve(filteredUsers);
      },
      create: (email: string, password: string) => {
        const user = {
          id: Math.floor(Math.random() * 999999),
          email,
          password,
        } as User;
        users.push(user);
        return Promise.resolve(user);
      },
    };

    const module = await Test.createTestingModule({
      providers: [
        AuthService,
        { provide: UsersService, useValue: fakeUsersService },
      ],
    }).compile();

    service = module.get(AuthService);
  });

  it('can create an instance of auth service', async () => {
    expect(service).toBeDefined();
  });

  it('creates a new user with a salted and hashed password', async () => {
    const user = await service.signup('[email protected]', 'asdf');

    expect(user.password).not.toEqual('asdf');

    const [salt, hash] = user.password.split('.');
    expect(salt).toBeDefined();
    expect(hash).toBeDefined();
  });

  it('throws an error if user signs up with email that is in use', async () => {
    fakeUsersService.find = () =>
      Promise.resolve([{ id: 1, email: 'a', password: '1' } as User]);
    try {
      await service.signup('[email protected]', 'asdf');
    } catch (error) {
      return error;
    }
  });

  it('throws if sign in is called with an unused email', async () => {
    try {
      await service.signin('[email protected]', 'sdbadfbd');
    } catch (error) {
      return error;
    }
  });

  it('throws if sign in is called with an unused email', (done) => {
    fakeUsersService.find = () =>
      Promise.resolve([
        { email: '[email protected]', password: 'asdfgh' } as User,
      ]);
    service.signin('emailaddress', 'adfgbd').catch(() => done());
  });

  it('returns a user if correct password is provided', async () => {
    const inMemoryUser = await service.signup('[email protected]', 'mypassword');
    console.log(inMemoryUser);

    const user = await service.signin('[email protected]', 'mypassword');
    expect(user).toBeDefined();
  });
});

GA4 – Browser back function doesn’t work with gtag.js

I’m trying to trigger an event in GA4 with DTM (Adobe Dynamic Tag Management) for my client.
I put following script1 in <head> section and script2 in top of <body> section. The event seems being fired properly so far since the clicks and views are counted on Google Analytics realtime page and DebugView.

But when I use browser back function after I clicked <a>, soon after Navigated to the previous page, Navigated to current page again. If I press the browser back again, the screen transits to the 2 previous page.

I could find this issue on

  • MacOS Google Chrome incognito mode, Safari
  • iOS Google Chrome, Safari
  • Android Google Chrome

As long as you DON’T have js plugin on your browser, it seems occur.
How can I fix this issue?

Thank you for your help.

script1

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-XXXXXXXXXX');
</script>

script2

/**
 * google analytics setting
 */
jQuery(function ($) {
  if (typeof gtag === "undefined") {
    return;
  }

  gtag("config", "G-XXXXXXXXXX", { transport_type: "beacon" });

  $("a[data-gaevent]").on({
    click: function (event) {
      var href = $(this).attr("href");
      var transitioned = false;

      var is_page_transition =
        href[0] !== "#" && $(this).attr("target") !== "_blank";
      if (is_page_transition) {
        event.preventDefault();
        setTimeout(pageTransition, 1000);
      }

      function pageTransition() {
        if (!transitioned) {
          transitioned = true;
          location.href = href;
        }
      }

      var tagStrings = $(this).data("gaevent");
      var tagCount = 0;
      var tagOutput;
      var isDone = false;

      tagOutput = tagStrings.split(/s+/);
      tagCount = tagOutput.length - 1;

      for (var i = 0; i <= tagCount; i++) {
        if (i === tagCount) {
          isDone = true;
        }
        sendGA(tagOutput[i], isDone);
      }

      function sendGA(gaEventTag, isDone) {
        gtag("event", "click_a", {
          eventAction: gaEventTag,
          eventLabel: gaEventTag.replace(/-.*$/, ""),
          eventCategory: location.href.replace(/#.*$/, ""),
          hitCallback: function () {
            if (is_page_transition && isDone) {
              pageTransition();
            }
          },
        });
      }
    },
  });
});

React.js Assigning new options to a React-Select menu based on the input of another menu

I’m working on what seems to be a rather odd problem and I can’t quite figure out how to go about resolving it.

The Issue:

I’m working on a React.js website and I’m attempting to change the options list of on React-Select element based on the selection of another React-Select element and I’m having difficulty making this work.

The basic idea is this. Say I have two lists of genres for books. One is a list of non-fiction genres and the other of fiction genres. The two select boxes are “genre-type-select” and the other is “genre-select”. The goal is to have the choice option list in genre-select be chosen based on what type of genre type I chose in the genre-type-select.

The Code:

I’ve omitted a large amount of code so that only the relevant material is here.

const [nonFictionGenreNamesList, setNonFictionGenreNamesList]=useState([]);
const [fictionGenreNamesList, setFictionGenreNamesList]=useState([]);

const genreSelectRef=useRef(null);
const genreOptions=[{value: "Non-Fiction", label: "Non-Fiction"}, {value: "Fiction", label: "Fiction"}];

const determineGenreSelectContents =(choice)=> {
    if(choice==="Non-Fiction"){
      genreSelectRef.options=[nonFictionGenreNamesList];
    } else {
      genreSelectRef.options=[fictionGenreNamesList];
    }
}

return (
    <label htmlFor="genreTypeSelect">Genre:</label>
        <Select options={genreOptions} defaultValue={genreOptions[0]} id="genre-type-select" className="select-box"
        onChange={(choice)=> determineGenreSelectContents(choice.value)} />

        <Select ref={genreSelectRef} options={nonFictionGenreNamesList} id="genre-select" className="select-box"
        onChange={(choice) => setBookGenreSelection(choice.value)}/>
);

The idea that I was on was that whenenver I selected a new genre type in the “genre-select-select”, it would then trigger an onChange effect in the “determineGenreSelectContents” method that would check the chosen value and then alter the options presented in the “genre-select” box accordingly using ref.

What I’ve Tried & Thoughts:

If there is a better way to do this without having to resort to useRef() then I don’t know it. I would prefer to avoid the ref system if at all possible though.

One thing I could do would be to simply remove the first select-box entirely and use a grouped options list. React-select certainly allows for that and it might even be a cleaner solution overall but I was really hoping to have two clearly separated lists that could be chosen at will.

Besides, if nothing else then this is a very interesting question to solve purely for the sake of solving it. During my research, I came across this post on Stack Overflow asking something nearly identical but it was never answered nor commented on so I know I’m not the first to have had this issue before.

Android Chrome clipboard write text/html does not appear to work

According to: https://chromestatus.com/feature/5357049665814528 it appears that Android Chrome does support clipboard copy of text/html. It references the following example url: https://hyper-silly-cross.glitch.me/ which does not appear to work on any Android devices I have tried.

Can other developers confirm if Android Chrome does support this functionality? It is working fine on other browsers, but not the mobile chrome.

Here is the typescript for our method we are trying to use… It appears to be failing silently and the promise is being resolved, it would be nice to at least have an exception thrown we could subscribe to.

  copyEmailHtml(emailText: string) {
    const blobInput = new Blob([emailText], { type: 'text/html' });
    const clipboardItemInput = new ClipboardItem({ 'text/html': blobInput } as any);

    navigator.clipboard.write([clipboardItemInput]).then(() => {
      notification.emailCopied = true;
      this.emailCopied.emit(notification);
    }, (error) => {
      this.showDialog('Error copying to clipboard.  Your browser is not supported');
    });
  }

Multiple buttons change the value of a single input text field of in a HTML form using JS

I am working on a piece of code that would allow me to press different “buttons” to insert a value inside of a text type input of a HTML form.

Currently, I am able to get the code working with one button connected to an event listener to modify the value in the text field, however, when I tried to add multiple buttons to edit the same text field, for some reason, I cannot get it to work.

I’ve tried different work arounds such as to add individual event listeners to each button and add a parameter field to the main function, however, I still can’t get it to work for some reason.

Here’s the minimum reproducible code snippets for the HTML and JS:

const textField = document.querySelector('input[name = "textField"]');
var myElement = document.forms['Test']['textField'];

const validTextStrings = ["Hello World", "Goodbye World"]


var button = document.querySelector('input[name = "button"]');
//var button2 = document.querySelector('input[name = "button2"]');


button.addEventListener("click", updateTextField);



function updateTextField() {
  console.log("button pressed");
  console.log(button.value);
  if (allValidValues(button.value)) {
    myElement.setAttribute('value', button.value);
  }
}

function allValidValues(value) {

  for (i = 0; i < validTextStrings.length; i++) {
    if (value == validTextStrings[i]) {
      return true;
    }
  }
  console.log("Invalid value");
  return false;
}
<body>
  <form name="Test">
    <input type="button" name="button" value="Goodbye World" class=".btn">
    <input type="button" name="button2" value="Hello World" class=".btn">

    <input type="text" value='TEST' placeholder="TEXT NEEDS UPDATING" name="textField">
  </form>
</body>

adding new random number after a link on every press

the goal of my code is to generate a new link each time “generate” is pressed, so that i can find new songs for geometry dash without having to spam numbers.

i have tried the string below but every time the button were to be clicked, it would append a new set of numbers on the end. i wish for the program to not require a refresh

document.querySelectorAll("a").forEach(link =>
     link.setAttribute("href", link.getAttribute("href") + Math.floor(Math.random() * 111392.8) + 1)

this is my current attempt. i have gotten the goal of a new number on every button press with a refresh but the prefix of “https://www.newgrounds.com/audio/listen/” wont append to the start.

<!DOCTYPE html>
<html> 

<head> 
<link rel="stylesheet" href="CSS1.css">

<script>
  window.onclick = () => {
    document.querySelectorAll("a").forEach(link =>
     link.setAttribute("href", Math.floor(Math.random() * 111392.8) + 1)
    );
  };
</script>

</head>

<title>
Newgrounds Song Generator
</title> 

<body>

<h1>Click the button to visit a random song!</h1>

<a href="https://www.newgrounds.com/audio/listen/" target="_blank">
<button>
Generate
</button>
</a>

</body>

</html>

thank you for reading and i hope you can help! 🙂

Javascript error “_ not defined” with lodash and wordpress

I am having an issue with my wordpress page – as I am always getting this JS error:

Uncaught ReferenceError: _ is not defined

The line of code it is referring to, is the _.noConflict(); statement below. However, as you can see, the lodash is just loaded right above it, and should have provided the _ variable. Any thoughts why this is happening?

<script type='text/javascript' defer src='https://website.com/wp-includes/js/dist/vendor/lodash.min.js'></script>
<script type='text/javascript'>
     window.lodash = _.noConflict();
</script>

I appreciate any hint

How to filter a large object from an array of values

I cannot seem to grasp how to use an array of values to filter an object. I am unfamiliar with terms/syntax to get this working. I thought I would need .filter => function but no success.
Hopefully the following dummy code can allow someone to see what I am trying to do – thanks

// Javascript array object
var str = "Organization A,Organization B,Organization X,Organization R,Organization P"
var arr = new Array(); 
arr = str.split(","); 

// object     
json=[
{"organization":"Organization A","host":"Computer 001"},
{"organization":"Organization B","host":"Computer 002"},
{"organization":"Organization C","host":"Computer 003"},
{"organization":"Organization A","host":"Computer 004"},
{"organization":"Organization D","host":"Computer 005"}
]

// result needed is to return the structure above that has organization(s) in arr 
// below is simple example for 1 successful test but need to get filter all in arr
// .map? .find? 
res = json.filter(f => f.organization==="Organization A") 

draftjs entity Content State to HTML

I am using draftjs in which users can type in anything and can also click a button on which I am inserting a IMMUTABLE entity.

const text = "foo";

const editorState = this.state.value;
const selectionState = editorState.getSelection();
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity("TOKEN", "IMMUTABLE", { time: new Date().getTime() });
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const modifiedContent = Modifier.insertText(contentState, selectionState, text, OrderedSet([ "INSERT" ]), entityKey);
const nextState = EditorState.push( editorState, modifiedContent, editorState.getLastChangeType() );

this.setState({value: nextState}, this.focus );

https://codepen.io/dakridge/pen/XgLWJQ

All this is working fine but when the editor state is saved and now I am trying to render the HTML from the saved ContentState in my webpage then I am not able to identify the immutable entity and apply styles to it or render it differently.

For ex, in the above example how can foo be rendered with a different color and how the saved timestamp say can be logged in the console when I hover over foo?

I am using draftjs-to-html to render html from draftjs output.

tried to recreate the _.only function but only works upon at least 2 iterations not one

function (testFunc) {
  const copyFunc = (a) => {
    const copyFunc2 = (b) => {
      return testFunc(a);
    };    
    return copyFunc2;
  };
  return copyFunc;
};

So the function returns the inner function upon first invocation.

Then returns the inner function of the inner function of the second invocation.

Then the second inner function (third invocation) actually returns the passed argument in the parent function and only invokes it with the character we gave it on the second invocation.

Ideally I want to achieve what I’m achieving over many invocations after only the first one if that makes sense.

Make global function with different arguments on google apps script

the title may not be very clear but here’s what I’m trying to do.I want to create a custom function on google apps script that takes a different value as an argument for each execution on the triggers that i’m going to set.
For example :

customfunction (formid)
{
var form = FormApp.openById(formid);
//rest of the function
}

then I want to call this custom function on a specific trigger and pass the formid argument.Is there any way to do that ? I’m still new to google apps script so I might be missing something

leaflet bounding rectangle error after enable edit

Users can input coordinates to a map then draw on map. However when I try to let the user edit the bounding rectangle by adding rectangle.enableEdit(); It get the following error. "Error: Must add layer to map before using getCenter()". If I remove enableEdit I can drag the map around. But with enableEdit on i get the error. What I am trying to accomplish is if a user puts in coordinates or if they use the draw rectangle button. I am trying to give them the same features. Where they can resize the bounding box and move the bounding box.

function drawRectangle()
{
if(rectangle) rectangle.remove(map);
....
...
var lat_lon = [[north,east],[south,west]];

rectangle = L.rectangle(lat_lon, { draggable: true ,redraw:true});
rectangle.addTo(map);
rectangle.enableEdit();
map.fitBounds(rectangle.getBounds());
}

Leaflet enableEdit Error

How to get same random number using Math.random at different places?

randomNum function returns the different values to diceNum.innerText and player.style.gridColumnStart, I want them to be same,How do I do that ?

const randomNum = () => {
  return Math.floor(Math.random() * 6) + 1;
};

diceBtn.addEventListener("click", () => {
  const diceNum = document.getElementById("dice-num");
  diceNum.innerText = randomNum();
  drawPlayer();
});

function drawPlayer() {
  playerBody.forEach((pos) => {
    const player = document.createElement("div");
    player.style.gridRowStart = pos.x;
    player.style.gridColumnStart = randomNum();
    player.setAttribute("id", "playerElement");
    gameBoard.appendChild(player);
  });
}