Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
How to write unit test for function that calls React.UseEffect in it ( code included )

Scroll.js

import React from "react";

export const ScrollToTop = ({ children, location }) => {
  React.useEffect(() => window.scrollTo(0, 0), [location.pathname]);
  return children;
};

Scroll.test.js

import React from "react";
import { ScrollToTop } from "./ScrollToTop";

describe("ScrollToTop", () => {
  it("", () => {
    expect(
      ScrollToTop({
        children: "some children",
        location: { pathname: "the path" }
      })
    ).toEqual();
  });
});

and the result I'm getting is enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should not call ScrollToTop as a function directly, this is what error message is complaining about.

React docs recommend the Testing Library for writing tests.

Here is an example of how you can write Scroll.test.js using the library above:

import React from "react";
import { render } from '@testing-library/react';
import { ScrollToTop } from "./ScrollToTop";

describe("ScrollToTop", () => {
  it('calls window.scrollTo()', () => {
    window.scrollTo = jest.fn(); // create a moack function and record all calls
    render(<ScrollToTop location={{ pathname: 'pathname' }}>Text</ScrollToTop>); // render a component

    expect(window.scrollTo).toHaveBeenCalledWith(0, 0); // check that scrollTo mock was called
  });
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!