nri-http-0.3.0.0: Make Elm style HTTP requests
Safe HaskellNone
LanguageHaskell2010

Http.Mock

Description

Stub out Http requests in tests.

Synopsis

Documentation

stub :: (HasCallStack, Typeable a) => List (Stub a) -> (Handler -> Expectation) -> Expectation' (List a) Source #

Stub out http requests in a bit of code. You can use this if you don't want your tests to make real http requests, and to listen in on the http requests it is attempting to make.

stub takes a function that it calls instead of making a real http request. That function should return the response string and a optionally some information about the http request. You'll get back the information collected for each outgoing http request so you can run assertions against it.

test "Stubbed HTTP requests" <| \_ -> do
  urlsAccessed <-
    Http.Mock.stub
      [mkStub (\req -> Task.succeed (Http.url req, "Response!" :: Text))]
      ( \http ->
          Expect.succeeds <| do
            _ <- Http.get http "example.com/one" Http.expectText
            _ <- Http.get http "example.com/two" Http.expectText
            Task.succeed ()
      )
  urlsAccessed
    |> Expect.equal ["example.com/one", "example.com/two"]

data Stub a Source #

A stub for a single request type. If your test body can perform multiple different kinds of http requests, you'll want one of these per request type.

mkStub :: (Typeable e, Typeable expect) => (Request' e expect -> Task e (a, expect)) -> Stub a Source #

Create a Stub.

Read request data

getHeader :: Text -> Request expect -> Maybe Text Source #

Read a header of the request. Useful to check what data got submitted inside a stub function.

This will return Nothing if no header with that name was set on the request.

getTextBody :: Request expect -> Maybe Text Source #

Read the body of the request as text. Useful to check what data got submitted inside a stub function.

This will return Nothing if the body cannot be parsed as UTF8 text.

getJsonBody :: FromJSON a => Request expect -> Result Text a Source #

Read the body of the request as json. Useful to check what data got submitted inside a stub function.

This will return an error if parsing the JSON body fails.

getBytesBody :: Request expect -> ByteString Source #

Read the body of the request as bytes. Useful to check what data got submitted inside a stub function.