Search code examples
htmlelm

Convert Elm Html nodes to string output


I have a viewFunc that returns some HTML. I would like to validate its return value. I wrote a test case using elm-test.

viewFunc |> Expect.equal (span [] [ text "hello world"]) 

It works well as long as my test case passes. However, when it fails, I get the following error:

    <internals>
    ╷
    │ Expect.equal
    ╵
    <internals>

It's not helpful at all. How could I have a more meaningful error message? Is there a way to stringify Html nodes? I looked around in the documentation of elm-html but haven't found anything.


Solution

  • Rather than comparing entire chunks of Html msg together, you'll get better results using the Test.Html.Query module (and corresponding Test.Html.Selector and Test.Html.Event modules). This allows you to create more targeted tests (e.g. testing whether a certain element has certain text or a certain class, rather than testing the entirety of the HTML structure). And the test failures do provide much more context to help you debug.

    I've built an example on Ellie, here's the basics of what a test might look like:

    test "Button has correct count" <|
        \() ->
            viewFunc
                |> Query.fromHtml
                |> Query.has [ Selector.text "hello world" ]
    

    The results in the console for a failure would be:

    > Hello World
    
        ▼ Query.fromHtml
    
            <div>
                Hello World!
            </div>
    
    
        ▼ Query.has [ text "hello world" ]
    
        > has text "hello world"