Testing Async Code With assert.rejects()

Kirsty’s suite also tests load_bookings(), which reads Snowline Hire’s bookings file: one test loads a one-booking file, and one expects a read of a missing file to fail. Both must wait for a file read, and the natural port of the second one fails in a confusing way.

Await the Loader in an Async Test

Kirsty’s load test is an async def function, which pytest runs through the pytest-asyncio plugin, using the asyncio_mode = "auto" setting in the provided pyproject.toml:

Language: Python
from fitting import load_bookings

async def test_load_bookings(tmp_path):
    path = tmp_path / "bookings.csv"
    path.write_text(
        "name,height,weight,boot,ability\n"
        "Morag Fraser,168,62,6,intermediate\n"
    )
    assert await load_bookings(path) == [{
        "name": "Morag Fraser", "height": 168,
        "weight": 62, "boot": 6, "ability": "intermediate",
    }]

In JavaScript, calling an async function gives back a promise of its result, much as calling an async def function gives back a coroutine. await unwraps the promise. An error thrown inside the function rejects the promise and arrives at the await, not at the call. That’s all you need to know about promises for now. They get a course of their own later on.

node:test needs no plugin. It waits for the promise that an async test function returns and fails the test if that promise is rejected, so anything you await inside the test counts. The port:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.