【问题标题】:Testing debouncing in Elm在 Elm 中测试去抖动
【发布时间】:2018-05-25 04:24:31
【问题描述】:

我正在尝试在我的 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))

似乎实现去抖动的不同方式并不能解决问题,因为它们都依赖于命令消息。

【问题讨论】:

标签: testing elm debounce elm-test


【解决方案1】:

根据您想要测试的具体内容,您可能会采用不同的方法。

如果你想测试

  1. 您在SearchInput 上的代码返回正确的命令:您可以考虑使用elm-testable

  2. elm 运行时正确执行Process.sleep 命令:这将属于integration/end-to-end test scenarios。因此,您需要使用端到端/JS 工具之一来测试完整编译的应用程序。

  3. 您的代码正确处理了Timeout x 消息:为此编写一个单独的测试用例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 2019-02-12
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-04
    • 2014-12-27
    相关资源
    最近更新 更多