首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用模拟服务工作者测试React App时,如何统计请求数?

在使用模拟服务工作者测试React App时,如何统计请求数?
EN

Stack Overflow用户
提问于 2021-04-22 02:06:37
回答 1查看 111关注 0票数 0

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

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

下面是处理程序的代码片段,如您所见,目前我已经在"Auth尝试“之后硬编码了"1”。

代码语言:javascript
复制
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
    }
  )
]

我的jest测试中,我确认了3次错误的日期:

代码语言:javascript
复制
// 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()
EN

回答 1

Stack Overflow用户

发布于 2021-05-14 07:15:45

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

下面是我推荐的方法:

代码语言:javascript
复制
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操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67201303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档