在我的应用程序中,用户输入他们的出生日期,发送一个请求,如果它与数据库中的道布匹配,他们就会被发送到下一个页面。如果不匹配,则向他们显示在其链接不再有效之前的尝试次数。他们有3次尝试。
我的问题是,如何使用模拟服务工作者模拟此功能?我需要记录这个请求被尝试和失败的次数。
下面是处理程序的代码片段,如您所见,目前我已经在"Auth尝试“之后硬编码了"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
}
)
]我的jest测试中,我确认了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()发布于 2021-05-14 07:15:45
您的总体想法是正确的:您可以通过在响应解析器中递增一个数字来跟踪请求的计数。
下面是我推荐的方法:
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操作。
https://stackoverflow.com/questions/67201303
复制相似问题