I have a simple component that has ref
attribute
In the useLayoutEffect
I am calculating isShown
value to show or hide <div id="isShown">XYZ</div>
element based on divRef.current.offsetWidth
.
here is my code example
import React, { useRef, useLayoutEffect, useState } from 'react';
export default function MyComponent() {
const [isShown, setIsShown] = useState(false);
const divRef = useRef(null);
useLayoutEffect(() => {
if (divRef.current) {
setIsShown(divRef.current.offsetWidth > 0)
}
}, [divRef])
return (
<div id="myDiv" ref={divRef}>
{isShown && <div id="isShown">XYZ</div>}
</div>
);
}
And I want to write some unit tests for it. So I am trying to mock useRef
current.offsetWidth
to set it to 123
(as example) - but it is always equal to 0
.
Any suggestions on what could be wrong here?
the is an example
import React from 'react';
import { configure, mount } from 'enzyme';
import MyComponent from './Comp';
import Adapter from "enzyme-adapter-react-16";
configure({ adapter: new Adapter() })
describe('MyComponent', () => {
it('should pass', () => {
jest.spyOn(React, "useRef").mockReturnValue({
current: {
offsetWidth: 123
}
});
const wrapper = mount(<MyComponent></MyComponent>);
expect(wrapper.find('#isShown')).toHaveLength(1);
});
});