Skip to content

Mocking allows you to selectively and temporarily replace the response you would typically receive from a request with your own code. It's primarily used for testing.


with_mocked_responses(mock, code)

local_mocked_responses(mock, env = caller_env())



A function, a list, or NULL.

  • NULL disables mocking and returns httr2 to regular operation.

  • A list of responses will be returned in sequence. After all responses have been used up, will return 503 server errors.

  • For maximum flexibility, you can supply a function that that takes a single argument, req, and returns either NULL (if it doesn't want to handle the request) or a response (if it does).


Code to execute in the temporary environment.


Environment to use for scoping changes.


with_mock() returns the result of evaluating code.


# This function should perform a response against
google <- function() {
  request("") |>

# But I can use a mock to instead return my own made up response:
my_mock <- function(req) {
  response(status_code = 403)
try(with_mock(my_mock, google()))
#> Warning: `with_mock()` was deprecated in httr2 1.0.0.
#>  Please use `with_mocked_responses()` instead.
#> Error in req_perform(request("")) : HTTP 403 Forbidden.