榆树中的模拟依赖 [英] Mock dependency in Elm

查看:56
本文介绍了榆树中的模拟依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在每个 elm 文件中,要导入的依赖项在顶部声明。
在测试应用程序时,有没有办法模拟依赖关系?

In every elm file, dependencies to be imported are declared at the top. Is there a way, while testing the application, to mock a dependency?

例如,假设我有一个使用HTTP模块制作ajax的应用程序请求。在测试模块时,我想避免发出实际的ajax请求,但我想拥有一个模拟的HTTP模块,该模块将仅出于测试目的而返回假响应。

For example, suppose I have an application using the HTTP module to make an ajax request. When I test my module, I would like to avoid to make the actual ajax request, but I'd like to have a mocked HTTP module which will return a fake response just for the sake of testing.

我该怎么做?

推荐答案

由于Elm是一种纯函数式语言,所以您通常不这样做不需要进行任何模拟,因为副作用仅限于与端口的交互。在大多数情况下,您可以直接调用要直接测试的函数。

Since Elm is a pure functional language, you often don't need to do any kind of mocking because side effects are limited to interaction with ports. Most of the time, you can just call the function you want to test directly.

请考虑以下将HTTP请求任务映射到Action的典型示例:

Consider this typical example of an HTTP request task being mapped to an Action:

type alias MyThing =
  { id : Int
  , name : String
  }

type Action
  = FetchData
  | ErrorOccurred String
  | DataFetched MyThing

myDecoder : Json.Decoder MyThing
myDecoder =
  Json.object2
    MyThing
    ("id" := Json.int) 
    ("name" := Json.string) 

fetchData : Effects Action
fetchData =
  Http.get myDecoder url
    |> Task.toResult
    |> Task.map httpResultToAction
    |> Effects.task

httpResultToAction : Result Http.Error MyThing -> Action
httpResultToAction result =
  case result of
    Ok thing ->
      DataFetched thing
    Err err ->
      ErrorOccurred (toString err)

在这里进行测试可以从中受益,

There are a few things that would benefit from testing here, but none of them require mocking.

您可能想测试 myDecoder 的JSON解码。您可以简单地创建一些好的和坏的JSON字符串,然后使用 Json.Decode.decodeString myDecoder 来测试最终结果是否符合您的期望。

You may want to test the JSON decoding of myDecoder. You could simply create some good and bad JSON strings and use Json.Decode.decodeString with myDecoder to test that the end result meets your expectation.

可能最需要单元测试的是 httpResultToAction 函数。同样,在此示例中,这不需要模拟。您所需要做的就是创建许多好的和坏的 Result 值并测试您的期望。

The thing that is probably most in need of unit testing is the httpResultToAction function. Again, in this example, this requires no mocking. All you need to do is create a number of good and bad Result values and test your expectations.

这篇关于榆树中的模拟依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆