Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample spec describing an app that listens for a keydown event
module SampleSpec exposing (main)
import Spec exposing (..)
import Spec.Step as Step
import Spec.Setup as Setup
import Spec.Markup as Markup
import Spec.Markup.Selector exposing (..)
import Spec.Markup.Event as Event
import Spec.Claim exposing (isSomethingWhere)
import Spec.Extra exposing (equals)
import Runner
import Json.Decode as Json
import Json.Encode as Encode
import Html exposing (Html)
import Browser.Events
keyDownSpec =
describe "keydown event"
[ scenario "pressing the up arrow" (
given (
Setup.initWithModel testModel
|> Setup.withUpdate update
|> Setup.withView view
|> Setup.withSubscriptions subscriptions
)
|> when "the up arrow is pressed"
[ Markup.target << document
, Event.trigger "keydown" <| Encode.object [ ("key", Encode.string "ArrowUp") ]
]
|> it "displays the key pressed" (
Markup.observeElement
|> Markup.query << by [ tag "div" ]
|> expect (isSomethingWhere <| Markup.text <| equals "ArrowUp")
)
)
]
main =
Runner.browserProgram
[ keyDownSpec
]
--- Sample App Below --->
type alias Model =
{ key: Maybe String
}
testModel : Model
testModel =
{ key = Nothing
}
type Msg
= GotKey String
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GotKey key ->
( { model | key = Just key }, Cmd.none )
view : Model -> Html Msg
view model =
Html.div []
[ Html.text <| Maybe.withDefault "No key pressed!" model.key ]
subscriptions : Model -> Sub Msg
subscriptions model =
Browser.Events.onKeyDown (keyDecoder GotKey)
keyDecoder : (String -> Msg) -> Json.Decoder Msg
keyDecoder tagger =
Json.field "key" Json.string
|> Json.map tagger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment