I want to test a navigation bar component's responsiveness using Jest. Any suggestions on how to do so? This is the navbar component
Navbar.js
import React, { useEffect, useRef } from 'react';
// custom hook that gives value of component width whenever it changes
const useContainerDimensions = myRef => {
const getDimensions = () => ({
width: myRef.current.offsetWidth,
});
const [dimensions, setDimensions] = useState({ width: 0 });
useEffect(() => {
const handleResize = () => {
setDimensions(getDimensions());
};
if (myRef.current) {
setDimensions(getDimensions());
}
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [myRef]);
return dimensions;
};
const Navbar = ({ children, filter }) => {
...
const { width } = useContainerDimensions(inputRef);
useEffect(() => {
if (width >= 890) {
//do stuff
}
if (width < 890) {
//do stuff
}
}, [width]);
...
return (
...
<div ref={inputRef}>component</div>
...
)
}
This was how I tried to test it, but it gives me an error at getDimensions saying myRef is null... not sure why. I'm guessing its because it can't fully read child components? or perhaps mq-polyfill isn't the right choice to stimulate different screen widths? I'm not sure. I would appreciate any help. Thank you! navbar.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import moxios from 'moxios';
import matchMediaPolyfill from 'mq-polyfill';
import Navbar from '../Navbar';
// stimulate different screen width
beforeAll(() => {
matchMediaPolyfill(window);
window.resizeTo = function resizeTo(width) {
Object.assign(this, {
innerWidth: width,
outerWidth: width,
}).dispatchEvent(new this.Event('resize'));
}
});
describe('Navbar component', () => {
beforeEach(() => {
moxios.install();
});
test('Rendered navbar with 700px width', () => {
window.resizeTo(700);
const tree = renderer
.create(
<Navbar>
<Navbar.Tab id="tabNavbar.inFlightOrders" label="In Flight Orders" component={null} />
<Navbar.Tab id="tabNavbar.activeService" label="Active Service" component={null} />
</Navbar>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
afterEach(() => {
moxios.uninstall();
});
});
Aucun commentaire:
Enregistrer un commentaire