Reputation: 745
I have a React component that does something like:
Component
class CallBackend extends React.Component{
constructor(){
super();
this.state = {
message:"",
loading:true
};
}
callService = ()=>{
axios.get("http://localhost:80/sample-url")
.then(response=>this.setState({loading:false, message:response.data}))
.catch(error=>this.setState({loading:false, message:error.message}));
};
render(){
return(<p>{this.state.loading}</p>);
}
}
and then, I want to test with mocha and chai that the state changes after I invoke the callService
method:
Unit Test
it("should change the state value after calling the service",()=>{
const clock = sinon.useFaketimers();
nock("http://localhost:80").get("/sample-url").reply(200,"ok");
const wrapper = shallow(<CallBackend/>);
expect(wrapper.state().loading).to.equal(true);
wrapper.instance().callService();
clock.tick(500);
wrapper.update();
expect(wrapper.state().loading).to.equal(false);
});
I've tried using wrapper.update()
or sinon.fakeTimer()
or even calling callService
as a Promise
wrapper.instance().callService().then(()=>{
expect(wrapper.state().loading).to.equal(false);
});
With no result: wrapper.instance().callService().then() is not defined
Any other suggestions? I really don't want to end up using setTimeout()
function
Upvotes: 1
Views: 50