Post by account_disabled on Jan 29, 2024 5:29:49 GMT
函数式编程和测试。也许你已经单独尝试过它们,但不知何故,你从未将其中任何一个作为你常规练习的一部分。它们本身听起来可能很天真,但是测试和函数式编程结合在一起可以产生不可抗拒的诱惑,几乎迫使您编写更干净、更紧凑、更易于维护的代码。 Pause Next Unmute Current Time 0:07 / Duration 2:00 Fullscreen 测试功能性 JavaScript — 碰撞测试假人端着一杯咖啡坐在电脑前 好消息是,同时使用这两种技术可以带来一些真正的优势。事实上,一旦你尝到了这种组合的甜蜜,你可能会发现自己像我一样对它上瘾,而且我敢打赌你会回来吃更多。 在本文中,我将向您介绍测试函数式 JavaScript 的原则。我将向您展示如何启动并运行 Jasmine 框架,并使用测试驱动的方法构建纯函数。 为什么要测试? 测试是为了确保应用程序中的代码执行您期望的操作,并在进行更改时继续执行您期望的操作,以便在完成后您拥有一个可以工作的产品。您编写一个测试,在一组定义的情况下定义您的预期功能,针对代码运行该测试,如果结果不是测试所说的那样,您会收到警告。在修复代码之前,您会不断收到该警告。 Learn to Code with JavaScript 然后你就会得到奖励。 是的,它会让你感觉良好。
测试有很多种形式,关于边界的划分还有进行健康辩论的空间,但简而言之: 单元测试验证隔离代码的功能 集成测试验证数据流和组件的交互 功能测试着眼于整个应用程序的行为 注意:不要因为有一种称为功能测试的测试而分心。这不是我们在这篇有关测试函数式 JavaScript 的文章中重点讨论 WhatsApp 号码数据 的内容。事实上,无论您是否在 JavaScript 中使用函数式编程技术,您用于对应用程序整体行为进行功能测试的方法可能都不会发生太大变化。函数式编程真正有用的地方是当你构建单元测试时。 您可以在编码过程中的任何时候编写测试,但我总是发现在编写您计划测试的函数之前编写单元测试是最有效的。这种做法称为测试驱动开发 (TDD),鼓励您在开始编写之前分解应用程序的功能,并确定您想要从每个代码部分获得什么结果,首先编写测试,然后编码以产生该结果。 TDD 的一个附带好处是,通常会迫使您与付费编写程序的人进行详细对话,以确保您所编写的内容确实是他们正在寻找的内容。毕竟,单次测试通过很容易。困难的是确定如何处理您将遇到的所有可能的输入,并在不破坏事物的情况下正确处理它们。 为什么是功能性的? 正如您可以想象的那样,编写代码的方式与测试的容易程度有很大关系。
有一些代码模式,例如将一个函数的行为紧密耦合到另一个函数,或者严重依赖全局变量,可能会使代码更难以进行单元测试。有时,您可能必须使用不方便的技术,例如“模拟”外部数据库的行为或模拟复杂的运行时环境,以便建立可测试的参数和结果。这些情况并不总是可以避免,但通常可以隔离代码中需要它们的位置,以便可以更轻松地测试其余代码。 函数式编程允许您独立处理应用程序中的数据和行为。您可以通过创建一组独立的函数来构建应用程序,每个函数独立工作并且不依赖于外部状态。因此,您的代码几乎变成了自我文档化,将明确定义的小型函数捆绑在一起,这些函数以一致且易于理解的方式运行。 Learn to Code with JavaScript 函数式编程通常与命令式编程和面向对象编程进行对比。JavaScript 可以支持所有这些技术,甚至可以混合搭配它们。函数式编程可能是创建命令式代码序列的一个有价值的替代方案,这些命令式代码序列跨多个步骤跟踪应用程序的状态,直到返回结果。或者通过复杂对象之间的交互来构建应用程序,这些对象封装了适用于特定数据结构的所有方法。 纯函数如何工作 函数式编程鼓励您使用微小的、可重用的、可组合的函数来构建应用程序,这些函数只做一件特定的事情,并每次为相同的输入返回相同的值。
测试有很多种形式,关于边界的划分还有进行健康辩论的空间,但简而言之: 单元测试验证隔离代码的功能 集成测试验证数据流和组件的交互 功能测试着眼于整个应用程序的行为 注意:不要因为有一种称为功能测试的测试而分心。这不是我们在这篇有关测试函数式 JavaScript 的文章中重点讨论 WhatsApp 号码数据 的内容。事实上,无论您是否在 JavaScript 中使用函数式编程技术,您用于对应用程序整体行为进行功能测试的方法可能都不会发生太大变化。函数式编程真正有用的地方是当你构建单元测试时。 您可以在编码过程中的任何时候编写测试,但我总是发现在编写您计划测试的函数之前编写单元测试是最有效的。这种做法称为测试驱动开发 (TDD),鼓励您在开始编写之前分解应用程序的功能,并确定您想要从每个代码部分获得什么结果,首先编写测试,然后编码以产生该结果。 TDD 的一个附带好处是,通常会迫使您与付费编写程序的人进行详细对话,以确保您所编写的内容确实是他们正在寻找的内容。毕竟,单次测试通过很容易。困难的是确定如何处理您将遇到的所有可能的输入,并在不破坏事物的情况下正确处理它们。 为什么是功能性的? 正如您可以想象的那样,编写代码的方式与测试的容易程度有很大关系。
有一些代码模式,例如将一个函数的行为紧密耦合到另一个函数,或者严重依赖全局变量,可能会使代码更难以进行单元测试。有时,您可能必须使用不方便的技术,例如“模拟”外部数据库的行为或模拟复杂的运行时环境,以便建立可测试的参数和结果。这些情况并不总是可以避免,但通常可以隔离代码中需要它们的位置,以便可以更轻松地测试其余代码。 函数式编程允许您独立处理应用程序中的数据和行为。您可以通过创建一组独立的函数来构建应用程序,每个函数独立工作并且不依赖于外部状态。因此,您的代码几乎变成了自我文档化,将明确定义的小型函数捆绑在一起,这些函数以一致且易于理解的方式运行。 Learn to Code with JavaScript 函数式编程通常与命令式编程和面向对象编程进行对比。JavaScript 可以支持所有这些技术,甚至可以混合搭配它们。函数式编程可能是创建命令式代码序列的一个有价值的替代方案,这些命令式代码序列跨多个步骤跟踪应用程序的状态,直到返回结果。或者通过复杂对象之间的交互来构建应用程序,这些对象封装了适用于特定数据结构的所有方法。 纯函数如何工作 函数式编程鼓励您使用微小的、可重用的、可组合的函数来构建应用程序,这些函数只做一件特定的事情,并每次为相同的输入返回相同的值。