I want to test the return value of event handlers invoked via simulate
Given the react component:
// Example code
function SomeParentComponent()
{
const someExpression = ....;
return <SomeComponent someEvent={() => someExpression ? true : false} />
}
and some test code:
// Test code
const wrapper = enzyme.shallow(<SomeParentComponent/>);
wrapper.find(SomeComponent).simulate('someEvent');
// TODO: verify the return value of someEvent handler.
The return value of simulate
can't be used because Simulate
returns a shallowWrapper (ie. wrapper.find(SomeComponent)
), instead of the return value of the event handler.
I should add that in this case, the event handler doesn't modify state, so I can't test what it did, it's a call back function.
(And I was hoping to be able to do something better than wrapper.find(SomeComponent).instance().props().someEvent()
)
.invoke(invokePropName)(...args) => Any API can to this.
Invokes a function prop.
E.g.
index.tsx
:
import React from "react";
import { useEffect } from "react";
export const SomeComponent = ({ someEvent }) => {
useEffect(() => {
someEvent()
}, [])
return <div>some component</div>
}
export function SomeParentComponent() {
const someExpression = 1;
return <SomeComponent someEvent={() => someExpression ? true : false} />
}
index.test.tsx
:
import { shallow } from "enzyme"
import React from "react"
import { SomeParentComponent, SomeComponent } from "."
describe('76204394', () => {
test('should pass', () => {
const wrapper = shallow(<SomeParentComponent />);
const actual = wrapper.find(SomeComponent).invoke('someEvent')()
expect(actual).toBeTrue();
})
})
Test result:
PASS stackoverflow/76204394/index.test.tsx (24.648 s)
76204394
✓ should pass (33 ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 72.73 | 50 | 50 | 66.67 |
index.tsx | 72.73 | 50 | 50 | 66.67 | 5-9
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 26.823 s
package version:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"react": "^16.14.0",