Categories
JavaScript Answers

How to find element’s position relative to the document with JavaScript?

Sometimes, we want to find element’s position relative to the document with JavaScript.

In this article, we’ll look at how to find element’s position relative to the document with JavaScript.

How to find element’s position relative to the document with JavaScript?

To find element’s position relative to the document with JavaScript, we can get the sum of the top value of the element and the document’s scrollTop value.

For instance, we write

element.getBoundingClientRect().top + document.documentElement.scrollTop;

to get position of the element relative to the top of the viewport with element.getBoundingClientRect().top.

And we add the viewport offset with scrollTop and add that to top.

Conclusion

To find element’s position relative to the document with JavaScript, we can get the sum of the top value of the element and the document’s scrollTop value.

Categories
JavaScript Answers

How to mock one specific method of a class with Jest and JavaScript?

Sometimes, we want to mock one specific method of a class with Jest and JavaScript.

In this article, we’ll look at how to mock one specific method of a class with Jest and JavaScript.

How to mock one specific method of a class with Jest and JavaScript?

To mock one specific method of a class with Jest and JavaScript, we can use the jest.spyOn method.

For instance, we write

import Person from "./Person";

test("Modify only instance", () => {
  let person = new Person("foo", "bar");
  let spy = jest.spyOn(person, "sayMyName").mockImplementation(() => "Hello");

  expect(person.sayMyName()).toBe("Hello");
  expect(person.bla()).toBe("bla");
  spy.mockRestore();
});

to mock the person.sayMyName method by calling spyOn and mockImplementation in the test.

The mockImplementation callback has the faked implementation of person.sayMyName.

Likewise, we can mock the same method for all tests by writing

import Person from "./Person";

beforeAll(() => {
  jest.spyOn(Person.prototype, "sayMyName").mockImplementation(() => "Hello");
});

afterAll(() => {
  jest.restoreAllMocks();
});

test("Modify class", () => {
  let person = new Person("foo", "bar");
  expect(person.sayMyName()).toBe("Hello");
});

We call jest.spyOn with Person.prototype and 'sayMyName and mockImplementation to do the mocking in the beforeAll callback.

The beforeAll callback runs before any tests are run.

Then we call restoreAllMocks to restore all mocks after all tests are run.

Conclusion

To mock one specific method of a class with Jest and JavaScript, we can use the jest.spyOn method.

Categories
JavaScript Answers

How to fix Phantom.js not waiting for full page load with JavaScript?

Sometimes, we want to fix Phantom.js not waiting for full page load with JavaScript.

In this article, we’ll look at how to fix Phantom.js not waiting for full page load with JavaScript.

How to fix Phantom.js not waiting for full page load with JavaScript?

To fix Phantom.js not waiting for full page load with JavaScript, we can call page.render in the setTimeout callback.

For instance, we write

page.open(address, (status) => {
  if (status !== "success") {
    console.log("Unable to load the address!");
    phantom.exit();
  } else {
    window.setTimeout(() => {
      page.render(output);
      phantom.exit();
    }, 1000);
  }
});

to call page.open with the address URL string to open the page.

And then we call setTimeout with a callback that calls page.render to render the page.

We specify that we wait 1 second before rendering.

Conclusion

To fix Phantom.js not waiting for full page load with JavaScript, we can call page.render in the setTimeout callback.

Categories
React Answers

How to fix cannot update a component while rendering a different component warning with React?

Sometimes, we want to fix cannot update a component while rendering a different component warning with React.

In this article, we’ll look at how to fix cannot update a component while rendering a different component warning with React.

How to fix cannot update a component while rendering a different component warning with React?

To fix cannot update a component while rendering a different component warning with React, we should call functions from props inside the useEffect callback or in functions in the component.

For instance, we write

const HomePage = (props) => {
  useEffect(() => {
    props.setAuthenticated(true);
  }, []);

  const handleChange = (e) => {
    props.setSearchTerm(e.target.value.toLowerCase());
  };

  return (
    <div key={props.restInfo.storeId} className="container-fluid">
      <ProductList searchResults={props.searchResults} />
    </div>
  );
};

to call the props.setAuthenticated function inside the useEffect callback when the component mounts.

If we call it in the component at the top level, then the function runs on every render, which triggers the warning.

Conclusion

To fix cannot update a component while rendering a different component warning with React, we should call functions from props inside the useEffect callback or in functions in the component.

Categories
JavaScript Answers

How to handle specific errors in JavaScript?

Sometimes, we want to handle specific errors in JavaScript.

In this article, we’ll look at how to handle specific errors in JavaScript.

How to handle specific errors in JavaScript?

To handle specific errors in JavaScript, we use the instanceof operator.

For instance, we write

try {
  //...
} catch (e) {
  if (e instanceof SpecificError) {
    // ...
  } else {
    throw e;
  }
}

to check if e in the catch block is an instance of the SpecificError constructor with

e instanceof SpecificError

Then we do what we want if that’s true.

Conclusion

To handle specific errors in JavaScript, we use the instanceof operator.