How to mock or ignore a task in supervision tree during unit tests

Right now my application tree starts a supervisor, as well as the rest of the phoenix application. The supervisor’s job is to initialize Cachex and run a Task, which will fetch an Auth token from an external service. We want to start the phoenix components of the application after the cache has been warmed up.

However, since running tests will start up the application’s supervision tree, so when we run our unit tests we are relying on an external service to startup every time. Is there a way to mock out the functionality in the task to not fetch token from external service?

The easiest solution is to add a config to control whether to fetch the token, then set that config to true/false depending on mix env. You can make the config value be {module name, function name} and call the function, this will achieve your goal of mocking out the functionality.

This sounds promising. Could you explain a bit more how to create and check the config values, and maybe provide a small code example?

I only want the task to not run in test environments. Would I be creating a key/value in test.exs (set to true), dev.exs and prod.exs (set to false)?

Then rely on Application.fetch_env(:myapp, :myconfig). If it is true, run code?

I would create a default in config.exs:

config :my_app, :fetch_token, true

It doesn’t hurt to copy that to dev/prod.exs.

Since the task should only be disabled in test env, override it in test.exs with config :my_app, :fetch_token, false.

Check for Application.get_env(:my_app, :fetch_token) == true then run code.

1 Like