Using search params (query)
URL search parameters, also known as query parameters, are a way to provide additional information to a request. They are encoded in the query string of a URL in key-value pairs. Search params are typically used in GET requests to filter, sort, or paginate data.
Using request search params
To use search params in your intercepted requests, declare their types in your schema.
schema.ts
import { HttpSchema } from '@zimic/http';
interface User {
id: string;
username: string;
}
type Schema = HttpSchema<{
'/users': {
GET: {
request: {
searchParams: {
q?: string;
page?: number;
size?: number;
orderBy?: 'createdAt:asc' | 'createdAt:desc';
};
};
response: {
200: { body: User[] };
};
};
};
}>;
Then, the request search params will be available in the searchParams
property, such as in
handler.with()
,
computed responses, and
handler.requests
. The search params are typed
and validated according to your schema, providing type safety and autocompletion.
- Local interceptor
- Remote interceptor
const handler = interceptor
.get('/users')
.with({
searchParams: {
q: 'user',
page: 1,
size: 10,
orderBy: 'createdAt:asc',
},
})
.respond((request) => {
console.log(request.searchParams.get('q'));
console.log(request.searchParams.get('page'));
console.log(request.searchParams.get('size'));
console.log(request.searchParams.get('orderBy'));
return {
status: 200,
body: users,
};
})
.times(1);
// Run the application and make requests...
console.log(handler.requests); // 1
console.log(handler.requests[0].searchParams.get('q'));
console.log(handler.requests[0].searchParams.get('page'));
console.log(handler.requests[0].searchParams.get('size'));
console.log(handler.requests[0].searchParams.get('orderBy'));
const handler = await interceptor
.get('/users')
.with({
searchParams: {
q: 'user',
page: 1,
size: 10,
orderBy: 'createdAt:asc',
},
})
.respond((request) => {
console.log(request.searchParams.get('q'));
console.log(request.searchParams.get('page'));
console.log(request.searchParams.get('size'));
console.log(request.searchParams.get('orderBy'));
return {
status: 200,
body: users,
};
})
.times(1);
// Run the application and make requests...
console.log(handler.requests); // 1
console.log(handler.requests[0].searchParams.get('q'));
console.log(handler.requests[0].searchParams.get('page'));
console.log(handler.requests[0].searchParams.get('size'));
console.log(handler.requests[0].searchParams.get('orderBy'));