Reactコンポーネントの基本的なモック形式

「JavaScriptでのテスト自動化」コースの開始を見越して 、一連の有用な記事の翻訳引き続き公開しています。


、このシリーズの最初の部分、我々はモックが実際に有用である理由を見ました。

このパートでは、Reactコンポーネントポピーの基本的なフォーマットについて説明します。

この記事のすべてのコードサンプルは、このリポジトリで入手できます。

dirv / mocking-react-components

Reactコンポーネントのモックの例。

使用しているコンポーネントをもう一度見てみましょう:BlogPagePostContent

ここにあり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 />
)

, .

, .

: .

: , . , .

. , .


- : " puppeteer".

:




All Articles