Last active
December 13, 2018 16:31
-
-
Save GeoDoo/71ade25b22cd046740ccfef0a375bc6f to your computer and use it in GitHub Desktop.
Component with async componentDidMount
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import axios from "axios"; | |
import "./App.css"; | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
posts: [], | |
error: "" | |
}; | |
} | |
async componentDidMount() { | |
try { | |
const response = await axios.get("https://jsonplaceholder.typicode.com/posts") | |
this.setState({ | |
posts: response.data | |
}); | |
} catch (e) { | |
this.setState({ error: e.message }); | |
} | |
} | |
render() { | |
const { posts } = this.state; | |
return ( | |
<div className="App"> | |
{posts.map(post => ( | |
<div key={post.id}> | |
<h2>{post.title}</h2> | |
<p>{post.body}</p> | |
</div> | |
))} | |
</div> | |
); | |
} | |
} | |
export default App; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { shallow } from "enzyme"; | |
import axios from "axios"; | |
import App from "./App"; | |
jest.mock("axios"); | |
it("fetches posts", done => { | |
const response = { | |
data: [{ id: 1 }, { id: 2 }, { id: 3 }] | |
}; | |
axios.get.mockResolvedValueOnce(response); | |
const wrapper = shallow(<App />); | |
setImmediate(() => { | |
expect(wrapper.state().posts).toEqual([{ id: 1 }, { id: 2 }, { id: 3 }]); | |
done(); | |
}); | |
}); | |
it("transmits a useful message when fetching is not successful", done => { | |
axios.get.mockImplementation(() => Promise.reject(new Error('error'))) | |
const wrapper = shallow(<App />); | |
setImmediate(() => { | |
expect(wrapper.state().error).toBe("error"); | |
done(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment