getResponse 函数旨在以编程方式解析请求。你不需要此功能即可使用 MSW 进行开发和测试。在 MSW 之上构建自定义包和功能时,你可能需要此功能。你可能还需要此功能来实现更复杂的请求流,例如模拟 批量 GraphQL 查询

¥The getResponse function is designed for programmatic resolution of requests. You don’t need this function to use MSW for development and testing. You may need this function when building custom packages and functionality on top of MSW. You may also need this function for more complex request flows, such as mocking batched GraphQL queries.


¥Call signature

function getResponse(
  handlers: Array<RequestHandler>,
  request: Request
): Promise<Response | undefined>


Source code for the `getResponse` function.



import { http, HttpResponse, getResponse } from 'msw'
const handlers = [
  http.get('http://localhost/user', () => {
    return HttpResponse.json({ name: 'John' })
const request = new Request('http://localhost/user')
const response = await getResponse(handlers, request)
const user = await response?.json()
// {"name":"John"}