You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elm中测试含File的Update函数:如何构造File值与模糊器?

Elm测试中构造File值及创建File模糊器的方法

一、构造测试用的File值

Elm的File是opaque类型(未暴露构造函数),无法直接手动创建,但可以通过elm-test提供的Test.Html.Event.file函数生成测试用实例:

import Test.Html.Event as Event
import File exposing (File)

-- 创建一个测试用的File
testFile : File
testFile = Event.file "test.txt" "text/plain" "测试文件内容"

在测试update函数时,直接用该实例构造消息即可:

import Test exposing (test)
import Expect
import Dict
import YourModule exposing (Model, Msg(..), update)

test "SelectedFiles消息更新selectedFiles字典" <|
    \() ->
        let
            initialModel = { selectedFiles = Dict.empty, fileUploadInfoList = [], modalSelectedFile = Nothing }
            testFile = Event.file "test.txt" "text/plain" "test content"
            (updatedModel, _) = update (SelectedFiles "file-key" [testFile]) initialModel { token = "", apiBaseUrl = "" }
        in
            Expect.equal (Dict.get "file-key" updatedModel.selectedFiles) (Just testFile)

如果需要验证文件属性(如名称、类型),可以使用File.name、File.mimeType等方法:

Expect.equal (File.name testFile) "test.txt"

二、创建File类型的模糊器

结合Fuzz模块和Event.file,可以生成随机的File实例用于模糊测试:

import Fuzz exposing (Fuzzer)
import Test.Html.Event as Event
import File exposing (File)

fileFuzzer : Fuzzer File
fileFuzzer =
    Fuzz.map3 Event.file
        -- 随机非空文件名
        (Fuzz.string |> Fuzz.filter (\name -> not (String.isEmpty name)))
        -- 随机常见MIME类型
        (Fuzz.oneOf
            [ Fuzz.constant "text/plain"
            , Fuzz.constant "application/json"
            , Fuzz.constant "image/png"
            , Fuzz.constant "application/pdf"
            ]
        )
        -- 随机文件内容
        Fuzz.string

使用该模糊器编写模糊测试:

test "随机File实例更新selectedFiles字典" <|
    Fuzz.with fileFuzzer <|
        \randomFile ->
            let
                initialModel = { selectedFiles = Dict.empty, fileUploadInfoList = [], modalSelectedFile = Nothing }
                (updatedModel, _) = update (SelectedFiles "random-key" [randomFile]) initialModel { token = "", apiBaseUrl = "" }
            in
                case Dict.get "random-key" updatedModel.selectedFiles of
                    Just savedFile ->
                        Expect.all
                            [ \_ -> Expect.equal (File.name savedFile) (File.name randomFile)
                            , \_ -> Expect.equal (File.mimeType savedFile) (File.mimeType randomFile)
                            ]
                            ()
                    Nothing ->
                        Expect.fail "文件未被添加到字典中"

内容的提问来源于stack exchange,提问作者a12345

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:48:24