【问题标题】:How to keep a count of number of requests when using mock service worker to test a React App?使用 mock service worker 测试 React App 时如何记录请求数?
【发布时间】:2021-07-15 23:17:33
【问题描述】:

在我的应用程序中,用户输入他们的出生日期,发送一个请求,如果它与数据库中的出生日期匹配,他们将被发送到下一页。如果不匹配,则会向他们显示他们在链接不再有效之前剩余的尝试次数。他们尝试了 3 次。

我的问题是,我将如何使用模拟服务工作者来模拟此功能?我需要记录这个请求被尝试和失败的次数。

这里是处理程序的代码 sn-p,你可以看到我现在在“验证尝试”之后硬编码了“1”。

rest.post(
    'https://myapiaddress/auth',
    (req, res, ctx) => {
      const enteredDateOfBirth = req.body.data.date_of_birth
      let returnResult
      if (enteredDateOfBirth === '1988-10-01') {
        returnResult = res(
          ctx.status(200),
          ctx.json({
            data: {
              basic: 'fdafhaioubeaufbaubsaidbnf873hf8faoi'
            }
          })
        )
      } else {
        returnResult = res(
          ctx.status(400),
          ctx.json({
            errors: [
              { code: 89, message: 'Wrong date of birth. Auth attempts: 1' }
            ]
          })
        )
      }
      return returnResult
    }
  )
]

我在其中确认错误日期 3 次的开玩笑测试:

// 1st attempt
  userEvent.click(confirmBtn)
  const warningAttemptsNum1 = await screen.findByText('1/3 attempts')
  const dateEntered = screen.getByText('(12/10/2010)')
  expect(warningAttemptsNum1).toBeInTheDocument()
  expect(dateEntered).toBeInTheDocument()
  // 2nd attempt
  userEvent.click(confirmBtn)
  const warningAttemptsNum2 = await screen.findByText('2/3 attempts')
  expect(warningAttemptsNum2).toBeInTheDocument()
  userEvent.click(confirmBtn)

  // Entering 3 times shows "link no longer valid" screen
  userEvent.click(confirmBtn)
  const linkNoLongerValidText = await screen.findByText(
    'This link is no longer valid'
  )
  expect(linkNoLongerValidText).toBeInTheDocument()

【问题讨论】:

    标签: reactjs jestjs react-testing-library msw


    【解决方案1】:

    您的总体想法是正确的:您可以通过在响应解析器中增加一个数字来跟踪请求的计数。

    我建议这样做:

    function withTimes(handler) {
      let attempts = 0
      return (req, res, ctx) => {
        attempts++
        handler(req, res, ctx, attempts)
      }
    }
    
    rest.post('/endpoint', withTimes((req, res, ctx, attempts) => {
      const MAX_ATTEMPTS = 3
      const dob = req.body.data.date_of_birth
    
      if (dob === '1988-10-01') {
        return res(ctx.json({ data: { basic: 'abc-123' }}))
      }
    
      return res(
        ctx.status(400),
        ctx.json({
          errors: [
            {
              code: 89,
              message: `Wrong date of birth. Attempts left: ${MAX_ATTEMPTS - attempts}`
            }
          ]
        })
      )
    }))
    

    我还看到您使用的响应体结构非常类似于 GraphQL。请注意,您应该使用GraphQL API 来处理 GraphQL 操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-07
      • 2016-12-12
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2022-09-14
      • 2016-07-22
      • 2017-10-21
      相关资源
      最近更新 更多