如何在Elixir测试中使用Finch旁路



我的项目使用Finch进行并行HTTP请求。

我试图在测试中添加旁路,但没有检测到HTTP请求。当我运行测试时,我得到了这个错误:

No HTTP request arrived at Bypass

这是我的测试:

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

这是我的MyClient模块:

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

Bypass不会接管HTTP连接,无论您命中哪个URI。它在本地主机上的一个随机端口上设置了一个测试服务器。您需要获取该端口(bypass.port(,使用它构造一个本地主机URI,并将该URI传递给您的测试,以便调用。

最新更新