0

In my app, the user enters their date of birth, a request is sent, and if it matches with the DOB in the database, they are sent to the next page. If it does not match, they are presented with the number of attempts they have left until their link is no longer valid. They have 3 attempts.

My question is, how would I mock this functionality using mock service worker? I would need to keep a count of the number of times this request has been attempted and failed.

Here is the code snippet of the handler, as you can see I have hardcoded the "1" after "Auth attempts" for now.

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
    }
  )
]

My jest test in which I confirm the incorrect date 3 times:

// 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()
Andy Pandy
  • 53
  • 4

1 Answers1

1

Your general idea is correct: you can keep a track of the count of requests made by incrementing a number in the response resolver.

Here's how I'd recommend doing it:

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}`
        }
      ]
    })
  )
}))

I also see that the response body structure you use is very similar to such of GraphQL. Note that you should use the GraphQL API to handle GraphQL operations.

kettanaito
  • 974
  • 5
  • 12