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);
});
});
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