I have a script that will generate html using Jinja.
<!-- more html here -->
<!-- more html here, too -->
I would like to make assertions like "assert that the html string has #someList and has 2 items: Item 1 and Item 2." without resorting to substring checking. e.g.
assert 'ul id="someList"' in renderedHtml
assert 'Item 1' in renderedHtml
assert 'Item 2' in renderedHtml
I imagine something like,
parsedHtml = parse(renderedHtml)
assert someList := parsedHtml.findBySelector("ul#someList")
assert someList.contains("Item 1")
assert someList.contains("Item 2")
Is installing an additional dependency (e.g. BeautifulSoup) an appropriate way to go about this?
Or does Jinja have a built-in functionality to help with these kinds of tests? I also use `pytest` if that matters.
There is nothing in Jinja. Although it is used for HTML in most cases, it can be used for any text based target, so having something for unit testing specifically would be a bit opinionated anyway IMHO.
So you could use any HTML parser to make sense of the rendered template within unit tests.
soup = bs4.BeautifulSoup(rendered_html, "html.parser")
list_node = soup.select_one("ul#someList")
assert list_node is not None
item_texts = list(list_node.stripped_strings)
assert "Item 1" in item_texts
assert "Item 2" in item_texts
assert list(list_node.stripped_strings) == ["Item 1", "Item 2"]