How to test used template and context in Django

How to test used template and context in Django

TDD in example

In TDD methodology first, we will write tests that we expect to be failed. Then write a minimum amount of code to get the tests to pass.

In our case, we need to test that the correct template was used and the ItemForm instance was passed in the context.

test_views.py

class HomePageTest(TestCase):

    def test_uses_home_template(self):
        response = self.client.get('/')
        self.assertTemplateUsed(response, 'home.html')

    def test_home_page_uses_item_form(self):
        response = self.client.get('/')
        self.assertIsInstance(response.context['form'], ItemForm)

Run the tests by python manage.py test or pytest. You will see that our tests fail.

To make them pass implement home_page view as the given below:

views.py

def home_page(request):
    form = ItemForm()
    return render(
        request, 
        'home.html',
        context={'form': form}
    )

Now, run the tests again. You should see that the tests pass now.