Testing Async Code With assert.rejects()

Snowline Hire’s fitting tests can check a customer object, but the booking site also reads customers from a file. That takes time, and a missing file can cause an error after you call the loader. Your tests need to wait for both the customer data and any reading error.

Kirsty’s Python suite already checks that journey. You’ll port its successful-load and missing-file checks so each result belongs to the test that requested it. Start with a booking that should load, keeping its file separate from the shop’s real bookings.

Wait for the Booking Data

In Python, pytest-asyncio runs async def tests. In your ski-fitting folder, install it with python -m pip install pytest pytest-asyncio. The supplied pyproject.toml sets asyncio_mode = "auto", so these tests need no marker. Save this beside fitting.py in test_fitting.py, then run python -m pytest -q:

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"
    )
    bookings = await load_bookings(path)
    assert bookings == [{
        "name": "Morag Fraser", "height": 168,
        "weight": 62, "boot": 6, "ability": "intermediate",
    }]

The assertion checks the loaded data after the read finishes. An async test in JavaScript works similarly: node:test waits for an async test function, with no plugin. Unlike calling a Python async def function, calling a JavaScript async function starts it and returns a promise, which you await to get the result.

Save this JavaScript version as fitting.test.js beside fitting.js, keeping the supplied package.json with "type": "module":

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.