我试图在我的Elm应用程序中测试一个删除函数,但是我想不出是如何实现的。
为了避免发出太多的http请求,将该删除应用于文本字段以进行模糊搜索,它是以这个示例https://ellie-app.com/jNmstCdv3va1为模型的,并遵循相同的逻辑。
type alias Model =
{ search : Maybe String
, searchResult : List User
, debouncingCounter : Int
}
init : Model
init =
{ search = Nothing
, searchResult = []
, debouncingCounter = 0
}
debounceTime : Time
debounceTime = 350 * Time.millisecond
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
(...)
SearchInput search ->
let
newCounter = model.debouncingCounter + 1
in
case search o
"" -> ({model | search = Nothing, searchResult = []}, Cmd.none)
_ ->
({ model | search = Just search, debouncingCounter = newCounter }
, Process.sleep debounceTime |> Task.perform (always (Timeout newCounter)))
Timeout int ->
if int==model.debouncingCounter then
(update SendSearch {model | debouncingCounter = 0 })
else
(update NoOperation model)
SendSearch ->
case model.search of
Nothing ->
(model, Cmd.none)
Just string ->
let
cmd = Http.send ReSendSearch <| postApiAdminUserSearchByQuery string
in
(model, cmd)
ReSendSearch result ->
case result of
Err _ ->
(model, Cmd.none)
Ok usersList ->
({model | searchResult = usersList}, Cmd.none )我想确保在打完电话后
update (searchInput "string") initHttp请求仅在debounceTime之后发送。
在用searchInput消息调用update函数之后,我可以轻松地测试模型。例如,这里我检查模型中"debouncingCounter“字段的初始值是否设置为1:
startDebounce : Test
startDebounce =
test "debouncingCounter is set to 1 after search input is updated" <|
\_ ->
Users.init
|> Users.update (Users.SearchInput "abc")
|> Tuple.first
|> .debouncingCounter
|> Expect.equal 1但是,我不知道如何测试延迟的Cmd Msg对模型的影响,因为我不能直接应用update函数返回的cmd值。
Process.sleep debounceTime |> Task.perform (always (Timeout newCounter))不同的实现方法似乎无法解决问题,因为它们都依赖于命令消息。
发布于 2018-05-28 13:33:19
根据具体要测试的内容,您可能会遵循不同的方法。
如果你想测试
SearchInput 上返回正确的命令:,您可以考虑使用elm-testable。Process.sleep 运行时正确地执行命令:,这将落入集成/端到端测试方案中。因此,您需要使用一个端到端/JS工具来测试完整的编译应用程序。Timeout x 消息的代码:只需编写一个单独的测试用例即可。https://stackoverflow.com/questions/50521544
复制相似问题