I am trying to test a react component using Jest and Enzyme. My componentDidMount
method/function
Real.jsx
// some code
class MyComponent extends React.Component {
componentDidMount() {
setTimeout (() => {
const { formVals : { eName, eSal }, changeVal } = this.props
console.log("changeVal function" + changeVal)
changeVal(someparam , someparam2)
}, 1000)
}
// some more functions
}
export default MyComponent
and my test code goes like
import MyComponent from '../../components/Real' //Real.jsx
jest.useFakeTimers();
test('test componentDidMount', () => {
var props = {
formVals: {
eName: 123,
eSal: 10000
},
changeVal: (x, y) => console.log(x)
}
var component = shallow <MyComponent {...props}/>
jest.runAllTimers(); // getting coverage for setTimeOut
component.update(); // getting coverage for setTimeOut
})
But I get the value of changeVal as undefined which means destructuring assignment is not working.
Kindly help on what might be an issue in this case.
Here you go.
const {
formVals: { eName, eSal },
changeVal
} = this.props;
Try this.
const { formVals : { eName, eSal }, changeVal } = this.props
Change const { formVals { eName, eSal }, changeVal } = this.props
to
const { formVals, changeVal } = this.props;
const { eName, eSal } = formVals;
or
const { formVals: { eName, eSal }, changeVal } = this.props
Update: Trying the repro the issue with snippet. Only change is I had to remove the ;
at end of console.log to avoid error.
var props = { formVals: { eName: 123, eSal: 10000, }, changeVal: (x, y) => console.log(x) }; const { formVals: { eName, eSal }, changeVal, } = props; changeVal("print this", "hello");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.