I am new to both mocking and Elixir, and trying to use the mocking library Mox to improve my tests coverage (mocking the dependencies), I was hoping to be able to create tests for most of my most critical status processors, and other calculations that my application need.
So I have been able to use the library, and as a first approach I got this mocked function to test fine:
test "Mocked OK response test" do
Parsers.MockMapsApi
|> expect(:parse_get_distance_duration, fn _ -> {:ok, "test_body", 200} end)
assert {:ok, "test_body", 200} == Parsers.MockMapsApi.parse_get_distance_duration({:ok, "", 200})
end
It is clear that this test is useless, since what I wanted to mock was this NESTED function from within another function, but only got to mock directly the function that was being called in the test.
So, pointing now my actual problem for a more simple test, that illustrates very well the scenario:
def get_time_diff_to_point(point_time) do
point_time
|> DateConverter.from_timestamp()
|> Timex.diff(Timex.now(), :seconds)
|> Result.success()
end
Clearly the Timex.now() will give me a new timestamp each time, making it impossible to test the calcucation successfully without a mock. So the real question is, How do I mock a NESTED function within the actual function being tested? In this case, I expect Timex.now() to give me the same value every time I run my test... Here's what I got so far (clearly not working, but I think illustrates what I'm trying to do:
test "Mocked time difference test" do
Utils.MockTimeDistance
|> expect(:Timex.now(), fn -> #DateTime<2018-01-28 20:13:43.137007Z> end)
assert {:ok, 4217787010} == Utils.TimeDistance.get_time_diff_to_point(5734957348)
end