1
votes

How could I mock a specific api call similar to how python requests-mock works:

with requests_mock.mock() as m:
    m.get('http://test.com', text='data')
    requests.get('http://test.com').text

In this example every call to http://test.com inside the with statement will be mocked

So in elixir, for example, I have this:

defmodule API do

  # makes a call to an external API I dont want to test
  def make_call do
    ...
  end
end

defmodule Item do

  alias API

  # function I actually want to test
  def build_request do
    API.make_call
    # stuff I want to test
  end

end

So let's say I want to test build_request mocking make_call

I tried this package https://github.com/jjh42/mock but what this package does is to override whole API module with for example a mock for make_call method but you also lose all the other functions of the API module and I dont want that.

How could I mock that call?

Here in another example I saw https://hashrocket.com/blog/posts/mocking-api-s-with-elixir

# mocking a github api call directly
@github_api.make_request(:get, "/users/#{username}")

But it's the same issue, it mocks the request straight in the test, my issue is when the mock needs to be done in an inner function not straight away.

1

1 Answers

1
votes

Dependency injection is your friend:

def build_request(caller \\ API) do
  caller.make_call
  # stuff I want to test
end

And in tests you supply a parameter to the call to build_request:

build_request(TestAPI)

For the details please refer to this brilliant writing by JoseĢ Valim.