Frontend testing verifies that an application's user-facing interface behaves correctly without depending on a live backend. Isolate the backend with a mock, launch the app through AppTest, and assert both initial state and visible UI behavior. section 11.4.1
A practical frontend test typically checks:
- Whether the initial interface contains the expected sidebar input and search button. section 11.4.1
- Whether a search stores mock results in session state and renders the expected number of expanders. section 11.4.1
- Whether rendered movie details include each item's overview and rating. section 11.4.1
Testing a movie search interface
Create a MockBackend with the same methods as Backend, configure a pytest fixture with AppTest.from_file("frontend.py"), enter "test movie", click Search, and compare the resulting session state and expanders with mock data. section 11.4.1
Listing 11.7 Testing the frontend
import pytest
from unittest.mock import patch
from streamlit.testing.v1 import AppTest
from mock_data import MOCK_RESULTS
class MockBackend:
@staticmethod
def get_poster_url(path):
return "https://mock-image-server.com/poster.jpg"
def __init__(self, api_key):
self.api_key = api_key
def search_movies(self, query):
return MOCK_RESULTS
@pytest.fixture
def setup_app():
at = AppTest.from_file("frontend.py")
at.secrets["api_key"] = "test_api_key"
return at
@patch("backend.Backend", MockBackend)
def test_initial_state(setup_app):
at = setup_app
at.run()
# Check if sidebar has search input field and button
assert len(at.sidebar.text_input) == 1
assert len(at.sidebar.button) == 1
assert "Search" in at.sidebar.button[0].label
# Check that results are not visible initially
assert "results" not in at.session_state
assert len(at.expander) == 0
Browse the complete test setup, including backend patching, secrets configuration, initial-state assertions, and mocked search behavior. section 11.4.1
