Last active
September 25, 2022 19:56
-
-
Save cheeyeo/df0c505a135ff3cba328 to your computer and use it in GitHub Desktop.
Example of mocking a web api in ExUnit in Elixir using Meck
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://github.com/eproxus/meck | |
| # add meck as a dependency in mix.exs | |
| defmodule GithubIssuesTest do | |
| use ExUnit.Case | |
| import :meck | |
| setup_all do | |
| new(Issues.GithubIssues) | |
| on_exit fn -> unload end | |
| :ok | |
| end | |
| test "successful fetch with user and a project" do | |
| # already decoded from raw json using jsx in pipeline | |
| mock_response = {:ok, [ | |
| [ | |
| {"url", "https://api.github.com/repos/elixir-lang/elixir/issues/2956"}, | |
| {"html_url", "https://github.com/elixir-lang/elixir/issues/2956"}, | |
| {"id", 52467010}, | |
| {"number", 2956} | |
| ] | |
| ] | |
| } | |
| # use meck to create a mock response | |
| expect(Issues.GithubIssues, :fetch, fn("elixir-lang", "elixir") -> mock_response end) | |
| # calls the actual function which makes the actual api call! | |
| # expect(Issues.GithubIssues, :fetch, fn("elixir-lang", "elixir") -> :meck.passthrough(["elixir-lang", "elixir"]) end) | |
| assert validate(Issues.GithubIssues) | |
| assert Issues.GithubIssues.fetch("elixir-lang", "elixir") == mock_response | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment