Testing pages with streamfields in Wagtail

398 Views Asked by At

I'm parsing HTML in a StreamField's richtext element via get_context, and want to be able to test that the context I've made contains the relevant modifications. But I'm really struggling to create a mock/stub that has a populated StreamField.

I'm looking at https://docs.wagtail.io/en/stable/advanced_topics/testing.html but need to do more than just test whether creation succeeds and the rich_text function etc. don't seem to output in the right format for other matters (like appending to the body attribute); I've had a little success with making fixtures via dumpdata but they're breaking other tests (presumably due to making the database inconsistent or something)

Are there any good examples out there of tests pre-populating a StreamField?

1

There are 1 best solutions below

0
On

... turns out it's remarkably simple, once it's been pointed out to you!

Once you've got your page (where pagetype is the module name and PageName the class name)

from modules.pagetype.models import PageName
page = PageName()

add some JSON to the StreamField object (here called body)

import json
page.body = json.dumps(
    [
       {"type": "rich_text", "value": "<h2>Hello, World!</h2>"},
       {"type": "rich_text", "value": "<h4>Here's another field</h4>"}
    ]
)

You may then want to then publish the post and look at the output.

from django.test import Client
page.save_revision().publish()
rv = Client().get(page.url)
assert "something_about_my_output_html" in str(rv.rendered_content)