Em antecipação ao início do curso "Automação de Teste em JavaScript", continuamos a publicar a tradução de uma série de artigos úteis
Na primeira parte desta série, vimos por que os mocks são realmente úteis.
Nesta parte, irei abordar o formato básico das papoulas do componente React.
Todos os exemplos de código para este artigo estão disponíveis neste repositório.
Exemplos de simulação de componentes React.
Vamos dar outra olhada nos componentes com os quais estamos trabalhando: BlogPage
e PostContent
.
Aqui está BlogPage
:
const getPostIdFromUrl = url =>
url.substr(url.lastIndexOf("/") + 1)
export const BlogPage = ({ url }) => {
const id = getPostIdFromUrl(url)
return (
<PostContent id={id} />
)
}
BlogPage
não faz muito mais do que exibir PostContent
. Mas tem algumas funcionalidades que nos interessam, nomeadamente analisar adereços url
para obter uma id
mensagem.
PostContent
um pouco mais complicado: ele chama uma função embutida do navegador fetch
para obter o texto de uma postagem de blog de uma URL /post?id=${id}
, onde id é o prop passado a ele.
export const PostContent = ({ id }) => {
const [ text, setText ] = useState("")
useEffect(() => {
fetchPostContent(id)
}, [id])
const fetchPostContent = async () => {
const result = await fetch(/post?id=${id})
if (result.ok) {
setText(await result.text())
}
}
return <p>{text}</p>
}
Na verdade, o que ele faz PostContent
não importa, porque não o veremos de novo!
BlogPage
BlogPage.test.js
. PostContent
, .
, PostContent
, BlogPage.test.js
, PostContent
.
PostContent
:
import { PostContent } from "../src/PostContent"
jest.mock("../src/PostContent", () => ({
PostContent: jest.fn(() => (
<div data-testid="PostContent" />
))
}))
.
jest.mock
. . ,import
. Jest . ,../src/PostContent
.
, , , .
jest.fn
(spy): , , .toHaveBeenCalled
toHaveBeenCalledWith
.
jest.fn
-, ( ).
, . React
div
- HTML , , !
data-testid
, , DOM.
React Testing Library
data-testid
, , , , , . , .
data-testid
.PostContent
. , .
React . 90% ( ) . 10% , .
, , BlogPage
.
, DOM
describe("BlogPage", () => {
it("renders a PostContent", () => {
render(<BlogPage url="http://example.com/blog/my-web-page" />)
expect(screen.queryByTestId("PostContent"))
.toBeInTheDocument()
})
})
, . screen.queryByTestId
DOM data-testid
PostContent
.
, , PostContent
.
queryByTestId
, queryByTestId
. React Testing Library : -, , getBy
queryBy
, -, , ID .
, - , queryByTestId
. , TestId
. : , . , .
: <div data-testid="ComponentName" />
- , .
getBy* queryBy*
getBy
, . , , (expect).
, :
expect(screen.getByTestId("PostContent"))
.toBeInTheDocument()
<PostContent />
, getByTestId. !
, , .
, TDD ( ), . queryBy
.
,
, , , PostContent
.
it("constructs a PostContent with an id prop created from the url", () => {
const postId = "my-amazing-post"
render(<BlogPage url={http://example.com/blog/${postId}} />)
expect(PostContent).toHaveBeenCalledWith(
{ id: postId },
expect.anything())
})
Jest, toHaveBeenCalledWith
, , PostContent
, .
React , ref . .
JSX <PostContent id="my-amazing-post" />
PostContent ({id: "my-amazing-post"})
.
, , .
expect.anything toHaveBeenCalledWith
, React , - (ref). , expect.anything()
, , .
expect.anything()
, Jest, .
, toHaveBeenCalled
, . toHaveBeenCalled
toHaveBeenCalledWith
.
. , :
jest.fn , , ,
<div />
.
data-testid
, DOM.
. ,
PostContent
<div data-testid = "PostContent" />
.
: , DOM, , .
?
, . ?
DOM, , :
export const BlogPost = () => {
PostContent({ id: "my-awesome-post" })
return null
}
- . : , , JSX . , , .
, , ?
:
export const BlogPost = () => (
<PostContent />
)
, .
, .
: .
: , . , .
. , .