Multiple calls to mocked api with different responses (Mox)

Good day, y’all!

I’m trying to mock two API calls to the same route, with different paraments and, therefore, different responses:

expect(FliptMock, :evaluate, 2, fn
        %{
          flagKey: "flag1",
          entityId: @user_id,
          context: %{cohortId: @cohort_id}
        } ->
          {:ok, %{match: true, value: ""}}
      end)
      
      expect(FliptMock, :evaluate, 2, fn
        %{
          flagKey: "flag2",
          entityId: @user_id,
          context: %{cohortId: @cohort_id}
        } ->
          {:ok, %{match: false, value: ""}}
      end)

However, the implementation above returns an error saying that there was no match in the anonymous function.

** (FunctionClauseError) no function clause matching in anonymous fn/1 in ModuleName."test GET /show_route returns ok when no commit is identified"/1

How should I do it? Thank you!

You can pattern match in the anonymous function:

expect(FliptMock, :evaluate, 2, fn
  %{
    flagKey: "flag1",
    entityId: @user_id,
    context: %{cohortId: @cohort_id}
  } ->
    {:ok, %{match: true, value: ""}}

  %{
    flagKey: "flag2",
    entityId: @user_id,
    context: %{cohortId: @cohort_id}
  } ->
    {:ok, %{match: false, value: ""}}
end)
4 Likes

It worked! Thank you :grinning: