I'm using Jest/Enzyme to test a React/TypeScript application and I'm having a hard time trying to write a test to assert if a button shows up after a certain period of time:
Here's a very simplified version of the component to be tested:
import { StyledNotifyButton } from './styles'; //style-component element const SomeComponent = (): ReactElement => { const [showNotifyButton, toggleNotifyButton] = useState(false); useEffect(() => { setTimeout(() => toggleNotifyButton(true), 5000); }, [toggleNotifyButton]); return ( <div> <StyledNotifyButton visible={showNotifyButton} /> </div> );
Here's the test:
describe('< FailingTest >', () => { let wrapper: ReactWrapper; beforeAll(() => { wrapper = mount(<SomeComponent />); }); it('should display the notify button only after X seconds', done => { let notifyButton = wrapper.find('StyledNotifyButton'); jest.spyOn(React, 'useEffect').mockImplementation(f => f()); expect(notifyButton.prop('visible')).toBe(false); jest.useFakeTimers(); setTimeout(() => { wrapper.update(); notifyButton = wrapper.find('NotifyButton'); expect(notifyButton.prop('visible')).toBe(true); wrapper.unmount(); done(); }, 5000); jest.runAllTimers(); });
I have already tries using fakeTimers, advanceTimersByTime, runAllTimers as explained in Just Timer Mocks
I've tried setTimeouts, as discussed here
Manually firing useEffect, as here or here
And many other ways... but I always get
expect(received).toBe(expected) // Object.is equality Expected: true Received: false
Any ideas on how to correctly get the visibility change after the timeout?? Thanks!
https://stackoverflow.com/questions/67440874/how-can-i-test-a-component-style-modified-by-a-settimeout-fired-on-useeffect May 08, 2021 at 03:46AM
没有评论:
发表评论