decodeelm

Elm testing: how to check if a Result is an Err?


I'm writing tests for functions that return a Result. How do I test that it "is" an Err (or an Ok, for that matter) ?

\() -> Expect.equal expectedFailure (Err _)

does not work.

How does one decode a non-parameter?


Solution

  • There may well be a more elegant solution I've missed, but I personally would just write a helper function.

    resultOk result =
        case result of
            Ok _ -> True
            Err _ -> False
    

    then in your tests

    Expect.true "expected this to be OK" (resultOk <| Ok "All good")
    Expect.false "expected this to be an error" (resultOk <| Err "Oh no!")
    

    Expect.true and Expect.false take a string to print if the test fails, and then an expression that should be true (in the case of Expect.true) or false (in the case of Expect.false).