Black Lives Matter. Please consider donating to Black Girls Code today.

How you can integration test your app by dash.testing

I have just figured out how you can integratoin test your Dash app and want to share it.

The documented way is …

def test_bsly001_falsy_child(dash_duo):
    app = dash.Dash(__name__)
    app.layout = html.Div(id="nully-wrapper", children=0)
    dash_duo.start_server(app)
    # ... tests ...

basically instantiating app within test function.
By this way, if you have a big Dash app, you have to reinstantiate (including layouts and callbacks) Dash app within a function. That’s very cumbersome.

Can we just call an app in app.py? You can.
My trick is to use import_app function.

Under directory called dash_test, let’s say we have following files.

__init__.py  
app.py  
test_one.py  

__init__.py is an empty file.

For app.py we have a test app.

# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

For test_one.py, just use import_app (see source code for documentation).

from dash.testing.application_runners import import_app


def test_one(dash_duo):
    app = import_app("dash_test.app")
    dash_duo.start_server(app)
    dash_duo.wait_for_text_to_equal("h1", "Hello Dash", timeout=4)

4 Likes

@takaakifuruse Thank you for the explanation. It helped me. BTW, how did you simulate the button clicks?