Categories
JavaScript Answers

How to properly make mock throw an error in Jest?

Sometimes, we want to properly make mock throw an error in Jest.

In this article, we’ll look at how to properly make mock throw an error in Jest.

How to properly make mock throw an error in Jest?

To properly make mock throw an error in Jest, we call the mockImplementation method and throw an error in the callback we call the method with.

For instance, we write

it("should throw error if email not found", async () => {
  callMethod
    .mockImplementation(() => {
      throw new Error("User not found [403]");
    })
    .mockName("callMethod");

  const query = FORGOT_PASSWORD_MUTATION;
  const params = { email: "user@example.com" };
  const result = await simulateQuery({ query, params });

  console.log(result);
  expect(callMethod()).rejects.toMatch("User not found [403]");
});

to call callMethod.mockImplementation with a callback that throws and error.

Then we use

expect(callMethod()).rejects.toMatch("error");

to check the callMethod throws an error with the given content.

Conclusion

To properly make mock throw an error in Jest, we call the mockImplementation method and throw an error in the callback we call the method with.

Categories
JavaScript Answers

How to add optional function in a TypeScript interface?

Sometimes, we want to add optional function in a TypeScript interface.

In this article, we’ll look at how to add optional function in a TypeScript interface.

How to add optional function in a TypeScript interface?

To add optional function in a TypeScript interface, we add a ? after the function name.

For instance, we write

interface IElement {
  name: string;
  options: any;
  type: string;
  value?: string;
  validation?(any): boolean;
}

to make the validation function optional by putting a ? after the function name.

Conclusion

To add optional function in a TypeScript interface, we add a ? after the function name.

Categories
JavaScript Answers

How to send a JSON to server and retrieving a JSON in return with JavaScript?

Sometimes, we want to send a JSON to server and retrieving a JSON in return with JavaScript

In this article, we’ll look at how to send a JSON to server and retrieving a JSON in return with JavaScript.

How to send a JSON to server and retrieving a JSON in return with JavaScript?

To send a JSON to server and retrieving a JSON in return with JavaScript, we use fetch.

For instance, we write

const dataToSend = JSON.stringify({
  email: "hey@mail.com",
  password: "101010",
});

const resp = await fetch(url, {
  credentials: "same-origin",
  mode: "same-origin",
  method: "post",
  headers: { "Content-Type": "application/json" },
  body: dataToSend,
});
const dataReceived = await resp.json();

to call fetch to make a post request to the url in an async function.

We call fetch with the headers and body to send the request headers and body.

And then we get the JSON response body from the resp.json method.

Conclusion

To send a JSON to server and retrieving a JSON in return with JavaScript, we use fetch.

Categories
JavaScript Answers

How to access a JavaScript object which has spaces in the object’s key?

Sometimes, we want to access a JavaScript object which has spaces in the object’s key.

In this article, we’ll look at how to access a JavaScript object which has spaces in the object’s key.

How to access a JavaScript object which has spaces in the object’s key?

To access a JavaScript object which has spaces in the object’s key, we use square brackets.

For instance, we write

myTextOptions["character names"].kid;

to get the "character names" property from myTextOptions.

Then we get the kid property from the returned object.

Conclusion

To access a JavaScript object which has spaces in the object’s key, we use square brackets.

Categories
JavaScript Answers

How to compress an image via JavaScript in the browser?

Sometimes, we want to compress an image via JavaScript in the browser.

In this article, we’ll look at how to compress an image via JavaScript in the browser.

How to compress an image via JavaScript in the browser?

To compress an image via JavaScript in the browser, we can use the compressorjs library.

To install it, we run

npm i compressorjs

Then we write

import axios from "axios";
import Compressor from "compressorjs";

document.getElementById("file").addEventListener("change", (e) => {
  const file = e.target.files[0];

  if (!file) {
    return;
  }

  new Compressor(file, {
    quality: 0.6,
    async success(result) {
      const formData = new FormData();
      formData.append("file", result, result.name);
      await axios.post("/path/to/upload", formData);
      console.log("Upload success");
    },
    error(err) {
      console.log(err.message);
    },
  });
});

to select the file input with getElementById.

Then we call addEventListener to listen to the change event.

In the event listener, we get the first selected file with

const file = e.target.files[0];

Then we create a Compressor object with the selected file and then get the compressed file from the success method.

In success, we upload the result with axios.post.

Conclusion

To compress an image via JavaScript in the browser, we can use the compressorjs library.