forked from testing-library/react-testing-library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.js
More file actions
52 lines (46 loc) · 1.37 KB
/
fetch.js
File metadata and controls
52 lines (46 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import React from 'react'
import axiosMock from 'axios'
import {render, Simulate, flushPromises} from '../'
// instead of importing it, we'll define it inline here
// import Fetch from '../fetch'
class Fetch extends React.Component {
state = {}
componentDidUpdate(prevProps) {
if (this.props.url !== prevProps.url) {
this.fetch()
}
}
fetch = async () => {
const response = await axiosMock.get(this.props.url)
this.setState({data: response.data})
}
render() {
const {data} = this.state
return (
<div>
<button onClick={this.fetch} data-testid="load-greeting">
Fetch
</button>
{data ? <span data-testid="greeting-text">{data.greeting}</span> : null}
</div>
)
}
}
test('Fetch makes an API call and displays the greeting when load-greeting is clicked', async () => {
// Arrange
axiosMock.get.mockImplementationOnce(() =>
Promise.resolve({
data: {greeting: 'hello there'},
}),
)
const url = '/greeting'
const {queryByTestId, container} = render(<Fetch url={url} />)
// Act
Simulate.click(queryByTestId('load-greeting'))
await flushPromises()
// Assert
expect(axiosMock.get).toHaveBeenCalledTimes(1)
expect(axiosMock.get).toHaveBeenCalledWith(url)
expect(queryByTestId('greeting-text').textContent).toBe('hello there')
expect(container.firstChild).toMatchSnapshot()
})