Comments (7)
I tried the above suggestion and that didn't work for me. I don't have time to investigate why (will try later) but I thought I'd let you know.
from msw.
Yup, this works:
rest.get(`${apiUrl}/books`, async (req, res, ctx) => {
if (!req.query.has('query')) {
return ctx.fetch(req)
}
const query = req.query.get('query')
let matchingBooks
if (query) {
matchingBooks = matchSorter(allBooks, query, {
keys: [
'title',
'author',
'publisher',
{threshold: matchSorter.rankings.CONTAINS, key: 'synopsis'},
],
})
} else {
// return a random assortment of 10 books not already in the user's list
matchingBooks = getBooksNotInUsersList(getUser(req).id).slice(0, 10)
}
return res(ctx.json({books: matchingBooks}))
}),
Thanks!
from msw.
Oh, also, is there a way to make the :query
param optional?
from msw.
Why is this project not using path-to-regexp
?
Historically, when this project started to use [email protected]
it required to have about this amount of abstraction to achieve what MSW needs:
With the latest version of path-to-regexp
it may make sense to re-introduce it to the library, although I'd like to have some reasons to do so. I'm using a tiny in-house alternative called node-match-path
, which may not catch all the use cases, but does what I need.
How to handle query params?
I wouldn't advise going with http://localhost:8989/api/book?query=:query
as it makes query position in the URI sensitive. For example, what if you have the following query: ?a=2&query=:query
. I'd still expect such URI to match, as it has the query
URL query parameter in place, but it won't match the provided RegExp. Generally, I don't think this is a scenario to be handled using path parameters.
Instead, you should specify which URL you would like to mock (without query) and decide on the mocking within the response resolver, basing your logic around req.query
:
import { composeMocks, rest } from 'msw'
composeMocks(
rest.get('http://localhost:8989/api/book', (req, res, ctx) => {
const { query } = req.query
// In case there is no such query parameter return the original response
if (!query) {
return ctx.fetch(req)
}
return res(
ctx.json({
title: 'The Magician',
author: 'Raymond E. Feist'
})
)
})
)
At the moment MSW performs no URL query parsing, which I think we should add. Handling query parameters was on my mind for some time, but I never got the moment to do it. This may be the right moment.
Please, would the solution suggested above satisfy your usage scenario? If not, elaborate why, I'd like to make this into the library in a proper way.
from msw.
In case it's helpful, here's what I have tried:
rest.get(`${apiUrl}/books`, async (req, res, ctx) => {
console.log('here we go')
if (!req.query.hasOwnProperty('query')) {
return ctx.fetch(req)
}
const {query} = req.query
let matchingBooks
if (query) {
matchingBooks = matchSorter(allBooks, query, {
keys: [
'title',
'author',
'publisher',
{threshold: matchSorter.rankings.CONTAINS, key: 'synopsis'},
],
})
} else {
// return a random assortment of 10 books not already in the user's list
matchingBooks = getBooksNotInUsersList(getUser(req).id).slice(0, 10)
}
await sleep()
return res(ctx.json({books: matchingBooks}))
}),
from msw.
Yes, accessing req.query
won't work at the moment, as it's not implemented. I'm tacking this in #76.
I've decided to parse the URL using new URL(req.url)
and provide the req.query = parsedUrl.searchParams
. Standard URLSearchParams
interface is handy when getting the query parameters and I think it should be favored over keeping req.query
as an object.
The usage of req.query
would be as follows:
res.get('/api/books', (req, res, ctx) => {
const bookId = req.query.get('id')
return res(ctx.json({ bookId })
})
from msw.
Released req.query
support in 0.10.0
. Published the Query parameters documentation to showcase how to access query parameters in response resolvers.
Internally, I made query params and hash to be dropped when request URL are compared.
@kentcdodds, could you please try it? I hope it works well for your use case.
from msw.
Related Issues (20)
- Add delay before each request HOT 3
- Mock a request that contains both query and path parameters
- TypeError: confirm is not a function HOT 7
- Failing to intercept an Axios request: Node 20.11 + Vitest 1.3.1 + MSW 2.2.1
- v2.2.2 does not intercept request in browser mode (CORS error) but v1.3.1 does HOT 3
- Infering the `boundary` callback arguments HOT 7
- support custom fetch option HOT 7
- support selecting interceptors HOT 1
- Set-Cookie responses containing commas are not handled correctly HOT 1
- HttpResponse.json() throwing TypeError: Right-hand side of 'instanceof' is not an object. HOT 1
- Request with FormData body makes Jest hang forever HOT 6
- TypeError: Right-hand side of 'instanceof' is not an object HOT 4
- Cannot read properties of undefined (reading 'url') HOT 5
- Mocked data getting empty string HOT 8
- "InvalidStateError: The object is in invalid state" when mocking rest api
- Unable to use msw/node for testing solid-js due to `resolve.conditions` set to `browser` HOT 5
- drop CommonJS support HOT 2
- quiet: true should supress RESPONSE LISTENER logs HOT 4
- Narrowing the response body type in `HttpResponse.json` HOT 16
- Error: No known conditions for "./browser" specifier in "msw" package HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from msw.