Mock requests based on query parameters #2347
-
I'm struggling right now to add handlers with query params to server. For instance, I would like to define the handlers like this await I.addInteractionToMockServer({
request: {
method: 'GET',
path: '/api/users',
queryParams: {
id: 1,
},
},
response: {
status: 200,
body: {
user: 1,
},
},
})
await I.addInteractionToMockServer({
request: {
method: 'GET',
path: '/api/users',
queryParams: {
id: 2,
},
},
response: {
status: 200,
body: {
user: 2,
},
},
}) Then when I call the mock service, I'd like to receive this let res = await restClient.sendGetRequest('/api/users?id=1')
expect(res.data).to.eql({ user: 1 })
res = await restClient.sendGetRequest('/api/users?id=2')
expect(res.data).to.eql({ user: 2 }) However, it always returns user: 1 when I call
May someone guide me or lead me to any docs that would tackle this? Thanks. Here is the implementation: async addInteractionToMockServer(interaction) {
let _path = `${config.host}${interaction.request.path}`
let _queryParams = '?'
if (interaction.request.queryParams) {
for (const [key, value] of Object.entries(interaction.request.queryParams)) {
_queryParams += `${key}=${value}`
}
}
_path += _queryParams
handlers.push(http[interaction.request.method.toLowerCase()](`${_path}`, () => {
return HttpResponse.json(interaction.response.body)
}))
await server.use(...handlers)
} |
Beta Was this translation helpful? Give feedback.
Answered by
kettanaito
Nov 3, 2024
Replies: 1 comment
-
Hi. You can implement the abstraction you want by moving it down to the response resolver that has the access to the actual query parameter values. function addInteractionToMockServer(interaction) {
handlers.push(
// 1. Do NOT add query parameters to "_path". They will be ignored.
http[interaction.request.method.toLowerCase()](`${_path}`, ({ request }) => {
const url = new URL(request.url)
const actualQuery = url.searchParams
// 2. Compare "actualQuery" and your "interaction.request.queryParams"
// to determine if this intercepted request should be matched.
// Implement this logic yourself.
if (matches(actualQuery, inteeraction.request.queryParams)) {
return HttpResponse.json(interaction.response.body)
}
})
)
} Useful materials
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
kettanaito
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. You can implement the abstraction you want by moving it down to the response resolver that has the access to the actual query parameter values.