enzyme
enzyme copied to clipboard
Use Effect not called when using mount - flush promises required (but there are no promises?!)
Current behavior
When testing whether a prop is executed in useEffect hook, using enzyme's mount, the test completes before useEffect is called. When searching for a solution issues with shallow rendering come up or if there is an async function happening somewhere. This shouldn't happen when there are no asynchronous functions being called.
Component
import React, { useEffect } from 'react';
// eslint-disable-next-line react/prop-types
const TestedComponent = ({ testEffect }) => {
useEffect(() => {
console.log('useEffect Called');
testEffect();
});
return (
<div>
Hello
</div>
);
};
export default TestedComponent;
Test
import React from 'react';
import { mount } from 'enzyme';
import TestedComponent from './TestedComponent';
describe('<TestedComponent />', () => {
it('renders Footer', () => {
console.log('testing started');
const testEffectMock = jest.fn();
const wrapper = mount(<TestedComponent testEffect={testEffectMock}/>);
console.log('component mounted');
expect(testEffectMock).toHaveBeenCalled();
});
});
I have tried:
- using wrapper.update() this doesn't work.
- I can use the flushPromises setTimeout/setImmediate which will work, referenced here: https://stackoverflow.com/questions/57006369/testing-asynchronous-useeffect
The issue I have is that there is no asynchronous function in useEffect. So I shouldn't have to do this.
Expected behaviour
Should execute useEffect hook when mounted before the assertion in the test happens.
I.e. in the console of the code above I should see: 'testing started' 'useEffect Called' 'component mounted' but 'useEffect Called' isn't logged, unless I use a setTimeout/setImmediate to wait until the next tick.
Don't understand why this isn't working. Thanks in advance for any insights/solutions. Apologies if there is something simple I'm missing or something stupid I have done.
Your environment
MacOS Catalina 10.15.3 node : v12.13.0 npm: 6.14.1
API
- [ ] shallow
- [x] mount
- [ ] render
Version
library | version |
---|---|
"enzyme": "^3.11.0", | |
"enzyme-adapter-react-16": "^1.10.0", | |
"react": "^16.8.2", | |
"react-dom": "^16.8.2", | |
"react-test-renderer": "^16.8.3" | |
"enzyme-adapter-react-16": "^1.10.0", |
Adapter
- [x] enzyme-adapter-react-16
- [ ] enzyme-adapter-react-16.3
- [ ] enzyme-adapter-react-16.2
- [ ] enzyme-adapter-react-16.1
- [ ] enzyme-adapter-react-15
- [ ] enzyme-adapter-react-15.4
- [ ] enzyme-adapter-react-14
- [ ] enzyme-adapter-react-13
- [ ] enzyme-adapter-react-helper
- [ ] others ( )
@fredlemieux Did you find any workaround? I am having this same issue, my mocked function/request calls in my useEffect
are not getting called.