I'm very new to Elm and I'm starting my first pet project using Elm 0.19.
I want to create a test case the JSON decoding in my application. The JSON returned from the server looks like this (everything is defined in a file called Frontend.elm
):
[
{
"gameId": "game1",
"player1": "player1",
"player2": "player2",
"winner": "player1",
"state": "ended"
},
{
"gameId": "game3",
"player1": "player1",
"state": "joinable"
}
]
My Elm models looks like this:
type Player =
Player String
type State
= Joinable
| Started
| Ended
type alias Game =
{ gameId : String
, player1 : Maybe Player
, player2 : Maybe Player
, winner : Maybe Player
, state : State}
and my decoding logic is defined like this:
gameStateDecoder : Decode.Decoder State
gameStateDecoder =
string
|> andThen (\stateAsString ->
case stateAsString of
"joinable" ->
succeed Joinable
"ended" ->
succeed Ended
"started" ->
succeed Started
unknown ->
fail <| "Unknown game state: " ++ unknown
)
playerDecoder : Decode.Decoder (Maybe Player)
playerDecoder =
(maybe string)
|> andThen (\maybePlayerString ->
succeed
<| case maybePlayerString of
Just player ->
Just (Player player)
_ ->
Nothing
)
gameListDecoder : Decode.Decoder (List Game)
gameListDecoder =
Decode.list gameDecoder
gameDecoder : Decode.Decoder Game
gameDecoder =
Decode.map5 Game
(field "gameId" string)
(field "player1" playerDecoder)
(field "player2" playerDecoder)
(field "winner" playerDecoder)
(field "state" gameStateDecoder)
Now I've tried to create a test case for this using the elm-explorations/test package:
import Frontend exposing (..)
import Expect exposing (equal)
import Test exposing (Test, test)
import Json.Decode exposing (decodeString)
decodesGameList : Test
decodesGameList =
test "Properly decodes a game list" <|
\() ->
let
json =
"""
[
{
"gameId": "game",
"state": "joinable"
}
]
"""
decodedOutput =
decodeString gameListDecoder json
in
equal
decodedOutput
(Ok
[ Game "game" Nothing Nothing Nothing Joinable ]
)
but when I try to run it using elm-test
I get this error:
<project path>/tests/FrontendTest.elm has an invalid module declaration. Check the first line of the file and make sure it has a valid module declaration there!
I don't understand what I'm doing wrong. The module is defined like this in Frontend.elm
:
module Frontend exposing (gameListDecoder, State(..), Game, Player(..))
I can perfectly well compile it using:
$ elm make src/main/elm/Frontend.elm --output src/main/resources/static/index.html
Success! Compiled 1 module.
You can actually find the code at github.
How can I solve this?
An Elm module is expected to have a module declaration at the top of the file, i.e.
module FrontendTest exposing (..)
should fix the problem in this case.