Search code examples
djangolighthouse

How do I run Lighthouse CLI during tests in Django?


I would like to run Lighthouse CLI during tests in Django. By default, Django tests don't run a server that can respond to HTTP requests, so this is not possible.

How can I run Lighthouse CLI during Django tests?


Solution

  • First, install Lighthouse CLI:

    $ npm install --save-dev @lhci/cli
    

    Then, modify package.json to modify the scripts section, like this:

    {
      "scripts": {
        "lhci": "lhci"
      }
    }
    

    You can run tests against a server that responds to HTTP requests using LiveServerTestCase or StaticLiveStaticTestCase, like this:

    from django.contrib.staticfiles.testing import StaticLiveServerTestCase
    import subprocess
    
    class Example(StaticLiveServerTestCase):
       def test_example(self):
           subprocess.check_call([
               'npm', 'run', '--', 'lhci', 'collect', '--url', self.live_server_url, '--no-lighthouserc',
           ])
           subprocess.check_call([
               'npm', 'run', '--', 'lhci', 'assert',
           ])
           # Optional:
           subprocess.check_call([
               'npm', 'run', '--', 'lhci', 'open',
           ])
    

    Now run this command:

    $ python manage.py test
    

    Note that you probably still want to test the performance of the website on the production server, as it may be quite different then the performance of the website on a local developer machine or the test server.