到目前为止,我得到的组件如下所示:
import React, { useState } from 'react'
import Axios from 'axios'
import { MagnifyingGlass } from 'icons'
import styles from './SearchBox.module.css'
function SearchBox({ setPhotos }) {
const [searchTerm, setSearchTerm] = useState('')
const handleTyping = (event) => {
event.preventDefault()
setSearchTerm(event.currentTarget.value)
}
const handleSubmit = async (event) => {
event.preventDefault()
if (searchTerm === '') {
return null
}
try {
const restURL = `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=${
process.env.REACT_APP_API_KEY
}&per_page=10&format=json&nojsoncallback=1'&text=${encodeURIComponent(searchTerm)}`
const { data } = await Axios.get(restURL)
const fetchedPhotos = data.photos.photo
setPhotos(fetchedPhotos)
setSearchTerm('')
} catch (error) {
if (!Axios.isCancel(error)) {
throw error
}
}
}
return (
<section className={styles.container}>
<form action="none">
<input
aria-label="Search Flickr"
placeholder="What are you looking for?"
value={searchTerm}
onChange={handleTyping}
/>
<button type="submit" aria-label="Submit search" onClick={handleSubmit}>
<MagnifyingGlass />
</button>
</form>
</section>
)
}
export default SearchBox
我对 TDD 的尝试看起来像这样
import React from 'react'
import { render, fireEvent, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import SearchBox from '.'
const fakeServer = setupServer(
rest.get('https://api.flickr.com/services/rest/?method=flickr.photos.search', (req, res, ctx) =>
res(ctx.status(200), ctx.json({ photos: { photo: [1, 2, 3] } }))
)
)
beforeAll(() => fakeServer.listen())
afterEach(() => fakeServer.resetHandlers())
afterAll(() => fakeServer.close())
// .. some other test using the fakeServer
test('throws an error if server error', async () => {
fakeServer.resetHandlers()
fakeServer.close()
const fakeFailingServer = setupServer(
rest.get('https://api.flickr.com/services/rest/?method=flickr.photos.search', (req, res, ctx) =>
res(
ctx.status(500),
ctx.json({
errorMessage: `Error! Something went terribly wrong!`,
})
)
)
)
fakeFailingServer.listen()
const fakeSetPhotos = jest.fn(() => {})
const { getByRole } = render(<SearchBox setPhotos={fakeSetPhotos} />)
const inputField = getByRole('textbox', { name: /search flickr/i })
const submitButton = getByRole('button', { name: /submit search/i })
await waitFor(() =>
expect(() => {
userEvent.type(inputField, 'Finding Walley')
fireEvent.click(submitButton)
}).toThrow()
)
fakeFailingServer.resetHandlers()
fakeFailingServer.close()
})
但它只是挂起......所以可以使用一些指导来了解我在这里做错了什么♂️</p>