我正在尝试在我的 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))
似乎实现去抖动的不同方式并不能解决问题,因为它们都依赖于命令消息。