Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot mock useRef value when using useLayoutEffect hook #7

Open
vkoman opened this issue May 20, 2021 · 0 comments
Open

Cannot mock useRef value when using useLayoutEffect hook #7

vkoman opened this issue May 20, 2021 · 0 comments

Comments

@vkoman
Copy link

vkoman commented May 20, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant