[Django]-Django-crispy-form: Unit test fails because of TypeError of helper object

2👍

Late answer, but ran up against this today. You need to spec the helper for your mock class to the FormHelper so that the “isinstance” call in the crispy templates passes. Easiest way to do this is to create a MagicMock subclass for the crispy form:

class MockCrispyForm(MagicMock):
    helper = MagicMock(spec=FormHelper)
    helper.template = False  # necessary for templates to render
    def is_valid(self):
        return True  # optional if you want form to validate

@patch('myapp.views.MyNewForm', MockCrispyForm())
class MyNewViewUnitTest(TestCase):
    def setUp(self):
        self.t = unittest.TestCase()
        self.t.request = HttpRequest()
        self.t.request.POST['data'] = 'data'
        self.t.request.user = Mock()

    def test_passes_POST_data_to_Form(self):
        event_new(self.t.request)
        myapp.views.MyNewForm.assert_called_once_with(
            data=self.t.request.POST
        )

Leave a comment