Categories
JavaScript Answers

How to spyOn a value property rather than a method with Jasmine and JavaScript?

Sometimes, we want to spyOn a value property rather than a method with Jasmine and JavaScript.

In this article, we’ll look at how to spyOn a value property rather than a method with Jasmine and JavaScript.

How to spyOn a value property rather than a method with Jasmine and JavaScript?

To spyOn a value property rather than a method with Jasmine and JavaScript, we can spy on the getter of the property.

For instance, we write

const spy = spyOnProperty(myObj, 'myGetterName', 'get'); 
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); 
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); 

in our test.

We call spyOnProperty with the arguments that leads to the myObj.myGetterNsme getter.

Then we call and.returnValue to mock the return value of the getter.

We call callThrough to call the getter.

Conclusion

To spyOn a value property rather than a method with Jasmine and JavaScript, we can spy on the getter of the property.

Categories
JavaScript Answers

How to await for a callback to return with JavaScript?

Sometimes, we want to await for a callback to return with JavaScript.

In this article, we’ll look at how to await for a callback to return with JavaScript.

How to await for a callback to return with JavaScript?

To await for a callback to return with JavaScript, we can wrap our callback code in the Promise constructor callback.

For instance, we write

const apiOn = (event) => {
  return new Promise((resolve) => {
    api.on(event, (response) => resolve(response));
  });
};

const test = async () => {
  return await apiOn("someEvent");
};

to create the apiOn function that returns a promise that we create with the Promise constructor.

We call it with a callback that calls resolve with the response to return that as its resolved value.

And then we call apiOn in the test function with the resolved value of the promise returned by apiOn.

Conclusion

To await for a callback to return with JavaScript, we can wrap our callback code in the Promise constructor callback.

Categories
JavaScript Answers

How to do email validation with JavaScript regular expression?

Sometimes, we want to do email validation with JavaScript regular expression.

In this article, we’ll look at how to do email validation with JavaScript regular expression.

How to do email validation with JavaScript regular expression?

To do email validation with JavaScript regular expression, we use the /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/ regex.

For instance, we write

const pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;

to assign the regex to pattern.

We use `w+to match any word before the@`.

[a-zA-Z_]+?\.[a-zA-Z]{2,3} matches the hostname part of the email address.

Conclusion

To do email validation with JavaScript regular expression, we use the /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/ regex.

Categories
JavaScript Answers

How to cancel a vanilla ECMAScript 6 Promise chain with JavaScript?

Sometimes, we want to cancel a vanilla ECMAScript 6 Promise chain with JavaScript.

In this article, we’ll look at how to cancel a vanilla ECMAScript 6 Promise chain with JavaScript.

How to cancel a vanilla ECMAScript 6 Promise chain with JavaScript?

To cancel a vanilla ECMAScript 6 Promise chain with JavaScript, we can use the Promise.race method.

For instance, we write

const actualPromise = new Promise((resolve, reject) => {
  setTimeout(resolve, 10000);
});
let cancel;
const cancelPromise = new Promise((resolve, reject) => {
  cancel = reject.bind(null, { canceled: true });
});

const cancelablePromise = Object.assign(
  Promise.race([actualPromise, cancelPromise]),
  { cancel }
);

to create actualPromise and the cancelPromise.

We call Promise.race with an array with the promise to return a promise with the result of the promise that’s finished first.

And we use that promise to create the cancelablePromise which merges the cancel property into the promise returned by race.

Conclusion

To cancel a vanilla ECMAScript 6 Promise chain with JavaScript, we can use the Promise.race method.

Categories
JavaScript Answers

How to automatically reconnect after it dies with WebSocket and JavaScript?

Sometimes, we want to automatically reconnect after it dies with WebSocket and JavaScript

In this article, we’ll look at how to automatically reconnect after it dies with WebSocket and JavaScript.

How to automatically reconnect after it dies with WebSocket and JavaScript?

To automatically reconnect after it dies with WebSocket and JavaScript, we set the WebSocket object’s onclose method to a function that reconnects after a set timeout.

For instance, we write

const connect = () => {
  const ws = new WebSocket("ws://localhost:8080");
  ws.onopen = () => {
    ws.send(
      JSON.stringify({
        //....
      })
    );
  };

  ws.onmessage = (e) => {
    console.log("Message:", e.data);
  };

  ws.onclose = (e) => {
    setTimeout(function () {
      connect();
    }, 1000);
  };

  ws.onerror = (err) => {
    console.error(err.message);
    ws.close();
  };
};

connect();

to create the connect function.

In it, we create a WebSocket object.

We set the onclose property to a function that calls connect in the setTimeout callback after a 1 second delay to reconnect after the connection is closed.

Conclusion

To automatically reconnect after it dies with WebSocket and JavaScript, we set the WebSocket object’s onclose method to a function that reconnects after a set timeout.