---
url: https://wvlet.org/uni/unitest/async.md
description: >-
  Async tests in UniTest — return an Rx or a Future from a test body on the JVM,
  Scala.js, and Scala Native, and check for leaked Rx subscriptions.
---

# Async Tests

Some code finishes later than the call that starts it: an HTTP request, a database
query, or work on another thread. A test body can reach its end before the result
arrives, and an assertion that runs after that is too late to fail the test.

Uni represents such work as an `Rx`. To test it, return the `Rx` from the test body.
UniTest runs it and reports its result on the JVM, Scala.js, and Scala Native, so a
test needs no blocking `await` and runs unchanged in a browser. Tests of code that uses
Scala's `Future` [work the same way](#future).

## Rx

An `Rx` is a description of work, and nothing runs until it is subscribed. UniTest
subscribes to the returned `Rx`, waits for its first value, and then cancels the
subscription:

```scala
import wvlet.uni.rx.Rx
import wvlet.uni.test.UniTest

class RxTest extends UniTest:
  test("map a value") {
    Rx.single(21).map { n =>
      n * 2 shouldBe 42
    }
  }

  test("use one result to get the next") {
    for
      a <- Rx.single(1)
      b <- Rx.single(a + 1)
    yield b shouldBe 2
  }

  test("expect a failure") {
    Rx.exception[Int](IllegalArgumentException("bad input"))
      .recover { case e: IllegalArgumentException => e.getMessage }
      .map { message =>
        message shouldBe "bad input"
      }
  }
```

* **Return it:** an `Rx` that is not the last expression of the body never runs, so its
  assertions are not checked.
* **Failures:** the test fails if the `Rx` ends with an exception. Use `recover` when you
  expect one.
* **No value:** an `Rx` that completes without a value fails the test, because the
  assertions in its `map` or `flatMap` never ran. To test that a stream is empty, return
  `rx.lastOption.toRx` with an assertion on the `Option`.

### Checking every value of a stream

Only the first value reaches the assertion, so a test of a stream with several values
collects them first:

```scala
class RxStreamTest extends UniTest:
  test("check all values") {
    Rx.fromSeq(Seq(1, 2, 3))
      .map(_ * 10)
      .scan(Seq.empty[Int])(_ :+ _)
      .lastOption
      .toRx
      .map { values =>
        values shouldBe Some(Seq(10, 20, 30))
      }
  }
```

## Future

Use this for code that returns a Scala `Future`. The test passes when the
returned `Future` succeeds, and fails when the `Future` or an assertion inside it fails:

```scala
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import wvlet.uni.test.UniTest

class FutureTest extends UniTest:
  test("double a value later") {
    Future(21).map { n =>
      n * 2 shouldBe 42
    }
  }
```

To use several results, chain them with `for`:

```scala
class FutureChainTest extends UniTest:
  test("use one result to get the next") {
    for
      a <- Future(1)
      b <- Future(a + 1)
    yield b shouldBe 2
  }
```

To check that a `Future` fails, turn its exception into a value with `failed`:

```scala
class FutureFailureTest extends UniTest:
  test("reject bad input") {
    Future[Int](throw IllegalArgumentException("bad input")).failed.map { e =>
      e shouldMatch { case _: IllegalArgumentException => }
    }
  }
```

Only the value the body returns is awaited. A `Future` that is not the last
expression of the body is not, so combine several with `flatMap` or
`Future.sequence`.

Tests of one suite run one at a time, so the next test starts after the returned
`Future` or `Rx` ends. Objects passed as [test arguments](./fixtures#design-integration)
stay open until then.

## Rx Subscription Leaks

`assertNoRxLeaks` fails when its block leaves an Rx subscription active, one
that was neither cancelled nor ended with `OnCompletion` / `OnFailure`:

```scala test
test("cancels its binding") {
  val counter = wvlet.uni.rx.Rx.variable(0)
  assertNoRxLeaks {
    val c = counter.subscribe(v => info(v))
    c.cancel
  }
}
```

It tracks the subscriptions the block starts on the test thread. See
[Finding Leaked Subscriptions](../rx/operators#finding-leaked-subscriptions).
