zoukankan      html  css  js  c++  java
  • [React Testing] Test Drive Mocking react-router’s Redirect Component on a Form Submission

    Once the data has been saved on the server, we’ll want to redirect the user to the home screen with react-router’s <Redirect /> component. Let’s go ahead and mock that component as well and verify that it’s being rendered with the correct props. We’ll have to make our test asynchronous so we can make that assertion because the <Redirect /> component is rendered after the async call happens.

    Component:

    import React from 'react'
    import { Redirect } from 'react-router'
    import { savePost } from './api'
    
    function Editor({ user }) {
      const [isSaving, setIsSaving] = React.useState(false)
      const [redirect, setRedirect] = React.useState(false)
      function handleSubmit(e) {
        e.preventDefault()
        const { title, content, tags } = e.target.elements
        const newPost = {
          title: title.value,
          content: content.value,
          tags: tags.value.split(',').map((t) => t.trim()),
          authorId: user.id,
        }
        setIsSaving(true)
        savePost(newPost).then(() => setRedirect(true))
      }
      if (redirect) {
        return <Redirect to="/" />
      }
      return (
        <form onSubmit={handleSubmit}>
          <label htmlFor="title-input">Title</label>
          <input id="title-input" name="title" />
    
          <label htmlFor="content-input">Content</label>
          <textarea id="content-input" name="content" />
    
          <label htmlFor="tags-input">Tags</label>
          <input id="tags-input" name="tags" />
    
          <button type="submit" disabled={isSaving}>
            Submit
          </button>
        </form>
      )
    }
    
    export { Editor }

    Test:

    import React from 'react'
    import { render, fireEvent, waitFor } from '@testing-library/react'
    import { Redirect as MockRedirect } from 'react-router'
    import { savePost as mockSavePost } from '../api'
    import { Editor } from '../extra/redirect'
    
    // Mock Router redirect
    jest.mock('react-router', () => {
      return {
        Redurect: jest.fn(() => null),
      }
    })
    
    jest.mock('../api')
    
    afterEach(() => {
      jest.clearAllMocks()
    })
    
    test('renders a form with title, content, tags, and a submit button', async () => {
      mockSavePost.mockResolvedValueOnce()
      const fakeUser = { id: 'user-1' }
      const { getByLabelText, getByText } = render(<Editor user={fakeUser} />)
      const fakePost = {
        title: 'Test Title',
        content: 'Test content',
        tags: ['tag1', 'tag2'],
      }
      getByLabelText(/title/i).value = fakePost.title
      getByLabelText(/content/i).value = fakePost.content
      getByLabelText(/tags/i).value = fakePost.tags.join(', ')
      const submitButton = getByText(/submit/i)
    
      fireEvent.click(submitButton)
    
      expect(submitButton).toBeDisabled()
    
      expect(mockSavePost).toHaveBeenCalledWith({
        ...fakePost,
        authorId: fakeUser.id,
      })
      expect(mockSavePost).toHaveBeenCalledTimes(1)
    
      await waitFor(() => expect(MockRedirect).toHaveBeenCalledWith({ to: '/' }, {}))
    })
  • 相关阅读:
    pycharm专业版破解
    XSS漏洞扫描工具:BruteXSS
    人生第一次成功的sql注入
    黑客学习之信息收集
    redhat 下搭建网站
    网络安全渗透--判断网站使用何种网页语言,判断网站所用服务器
    jqgrid表头上面再加一行---二级表头
    实验吧 burpsuie拦截修改请求
    实验吧 貌似有点难 伪造ip
    实验吧 这个看起来有点简单!&渗透测试工具sqlmap基础教程
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12819146.html
Copyright © 2011-2022 走看看