javascript - React testing with asynchronous setState -
i'm new react testing , i'm having hard time figuring out following issue:
i'm trying simulate input onchange event. it's text input filters results in table. interactivetable
has controlled input field (controlledinput
) , instance of facebook's fixeddatatable
.
this test:
let filter = reacttestutils.findrenderedcomponentwithtype(component, controlledinput); let input = reacttestutils.findrendereddomcomponentwithtag(filter, 'input'); input.value = 'a'; reacttestutils.simulate.change(input); console.log(component.state);
on input change component updates state value of input, since setstate
asynchronous, here console.log log out previous state, , can't query structure of component testing, because it's not updated yet. missing?
edit: clear, if make assertion in settimeout, pass, it's problem asynchronous nature of setstate.
i found 1 solution, overwrite componentdidupdate
method of component:
component.componentdidupdate = () => { console.log(component.state); // shows updated state let cells = reacttestutils.scryrenderedcomponentswithtype(component, cell); expect(cells.length).tobe(30); done(); };
this wouldn't possible if component had own componentdidupdate method, it's not solution. seems common problem, yet find no solution it.
normally when run similar scenarios when testing, try break things apart little. in current test, (depending on flavor of test framework), mock component's setstate
method, , ensure it's called expect when simulate change.
if want further coverage, in different test call real setstate
mock data, , use callback make assertions what's rendered, or ensure other internal methods called.
or: if testing framework allows simulating async stuff, try calling , test whole thing in 1 go.
Comments
Post a Comment