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

129
Views
Test if the windows location is correctly set

I am setting windows location in my useEffect hook as follows.

const MyComponent = (name) => {
  React.useEffect(() => {
    window.location.href = `/${name}/mypath${window.location.search}`
  }, []);

  return <Fragment/>;
};

I am looking to test that the href value matches correctly.

Thus I am mocking the data as follows and expecting the value to match following String.

www.test.com/name/mypath?param=1

But I end up with error saying that the window.location.href's value is actually the following.

/[object Object]/mypath?param=1

It is missing the host and also not capturing the name prop's value in the href. Could I get some advice on what I doing wrong? Thanks.

My test as follows.

jest.spyOn(React, 'useEffect').mockImplementation(f => f());

delete window.location;
window = Object.create(window);
const host = "www.test.com";
const search = '?param=1'
Object.defineProperty(window, "location", {
  value: {
    host,
    search
  },
  writable: true
});

describe('My tests', () => {
  const render = () => shallow(
    <MyComponent name='name' />
  );

  it('should pass', () => {
    const rendered = render();
    const url = 'www.test.com/name/mypath?param=1';
    expect(window.location.href).toEqual(url);
  });
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You forgot to destructure the props argument for your component,

It should be

const MyComponent = ({name}) => {
//rest of your code

}

The reason is component functions receive only one argument, which is an object with all the props you passed. What you did is just called it name. What I did is destructure the name property from the props object, i.e. took the value that was passed in the name prop

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!