You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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';
And I want to write some unit tests for it. So I am trying to mock useRefcurrent.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";
I have a simple component that has
ref
attributeIn the
useLayoutEffect
I am calculatingisShown
value to show or hide<div id="isShown">XYZ</div>
element based ondivRef.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 to123
(as example) - but it is always equal to0
.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);
});
});
The text was updated successfully, but these errors were encountered: