Skip to content

Instantly share code, notes, and snippets.

@brian-watkins
Last active October 31, 2020 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brian-watkins/3721115745e31bf17c25030539d0e3aa to your computer and use it in GitHub Desktop.
Save brian-watkins/3721115745e31bf17c25030539d0e3aa to your computer and use it in GitHub Desktop.
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