我试图在我的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") init
Http请求仅在debounceTime之后发送.
在使用searchInput消息调用更新函数后,我可以轻松地测试模型.例如,在这里我检查模型中“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对模型的影响,因为我无法直接应用更新函数返回的cmd值.
Process.sleep debounceTime |> Task.perform (always (Timeout newCounter))
似乎不同的实现去抖动的方法不会解决问题,因为它们都依赖于命令消息.
最佳答案 根据您要测试的具体内容,您可能会采用不同的方法.
如果你想测试
>您在SearchInput上的代码返回正确的命令:您可以考虑使用elm-testable
.
> elm运行时正确执行Process.sleep命令:这将属于integration/end-to-end test scenarios.因此,您需要使用端到端/ JS工具之一来测试完整的已编译应用程序.
>您的代码正确处理Timeout x消息:只需为此编写一个单独的测试用例.