预期“ JavaScript中的测试自动化”课程将开始 ,我们将继续发布一系列有用文章的翻译
在这一部分中,我将介绍React组件罂粟的基本格式。
此存储库中提供了本文的所有代码示例。
模拟React组件的示例。
让我们再来看一下我们正在使用的组件:BlogPage
和PostContent
。
这里是BlogPage
:
const getPostIdFromUrl = url =>
url.substr(url.lastIndexOf("/") + 1)
export const BlogPage = ({ url }) => {
const id = getPostIdFromUrl(url)
return (
<PostContent id={id} />
)
}
BlogPage
除了显示以外,除了没做其他的事情PostContent
。但是它具有我们感兴趣的一些功能,即解析道具url
以获取id
消息。
PostContent
稍微复杂一点:它调用浏览器内置函数fetch
以从URL获取博客文章的文本/post?id=${id}
,其中id是传递给它的道具。
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>
}
实际上,它的作用PostContent
并不重要,因为我们不会再看到它!
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 />
)
, .
, .
: .
: , . , .
. , .