Testing asynchronous code in Elixir

后端 未结 2 1160
不知归路
不知归路 2021-02-01 05:38

I want to test a function which is using Task.async

In order to make my test pass, I need to make it sleep for 100ms before assertions, otherwise the test p

2条回答
  •  感情败类
    2021-02-01 05:50

    When I cannot use José's approach involving assert_receive, I use a small helper to repeatedly do assertion / sleep, until the assertion pass or finally times out.

    Here is the helper module

    defmodule TimeHelper do
    
      def wait_until(fun), do: wait_until(500, fun)
    
      def wait_until(0, fun), do: fun.()
    
      def wait_until(timeout, fun) defo
        try do
          fun.()
        rescue
          ExUnit.AssertionError ->
            :timer.sleep(10)
            wait_until(max(0, timeout - 10), fun)
        end
      end
    
    end
    

    It can be used like this in former example:

    TSearch.search([q: "my query"])
    wait_until fn ->
      assert called TStore.store("some tweet from my fixtures")
      assert called TStore.store("another one")
    end
    

提交回复
热议问题