How to use bypass with Finch in Elixir tests?

987 views Asked by At

My project uses Finch to make parallel HTTP requests.

I tried to add bypass to my tests, but the HTTP requests are not being detected. When I run the test, I get this error:

No HTTP request arrived at Bypass

Here is my test:

defmodule MyClientTest do
  use ExUnit.Case, async: true

  setup do
    bypass = Bypass.open()
    {:ok, bypass: bypass}
  end

  describe "list_apps" do
    test "should have an expected app", %{bypass: bypass} do
      {:ok, contents} = File.read("test/apps.json")

      Bypass.expect(
        bypass,
        fn conn ->
          Plug.Conn.resp(conn, 200, contents)
        end
      )

      list_apps = MyClient.list_apps()
      assert length(list_apps) == 57
    end
  end
end

Here is my MyClient module:

defmodule MyClient do
  alias Finch.Response

  def child_spec do
    {Finch,
     name: __MODULE__,
     pools: %{
       "https://myapp.com" => [size: 100]
     }}
  end

  def applications_response do
    :get
    |> Finch.build("https://myapp.com/v2/apps.json")
    |> Finch.request(__MODULE__)
  end

  def handle_applications_response({:ok, %Response{body: body}}) do
    body
    |> Jason.decode!()
    end
  end

  def list_apps do
    handle_applications_response(applications_response())
  end

end
1

There are 1 answers

0
Phil Kulak On

Bypass doesn't take over the HTTP connection, no matter what URI you hit. It sets up a test server on localhost at a random port. You need to the get that port (bypass.port), construct a localhost URI using it, and pass that URI to your test, to be called.