为什么测试喜欢ie

by Evelyn Chan

通过伊芙琳·陈

为什么我现在喜欢测试,以及为什么您也应该如此。 (Why I now appreciate testing, and why you should, too.)

There’s a common misconception that writing tests slows down development speed. While the benefits of testing may not be immediately noticeable sometimes, it’s been my experience thus far that testing allows me to work faster in the long run, even on a small team.

有一个普遍的误解,认为编写测试会降低开发速度。 尽管有时有时无法立即注意到测试的好处,但到目前为止,根据我的经验,即使在一个小型团队中,测试也可以使我从长远来看可以更快地工作。

After implementing tests for a full-stack application, I’ve come to appreciate how useful it is to effectively test your apps and how it influences your coding ability.

在为全栈应用程序实施测试之后,我开始意识到有效测试应用程序的有用性以及它如何影响您的编码能力。

快速介绍一下测试堆栈的外观 (Quick intro to what a test stack looks like)

Jest is a testing library developed by Facebook that comes prepackaged with a bunch of cool methods to make testing easier. On a recent project, my team and I chose Jest because of its ease of use and its wide range of built-in functions that help streamline your testing. It’s very simple to set up and uses the Expect library for assertions.

Jest是由Facebook开发的测试库,它预包装了许多很酷的方法,以简化测试。 在最近的项目中,我和我的团队选择了Jest,因为它的易用性和广泛的内置功能有助于简化测试。 设置和使用Expect库进行断言非常简单。

Enzyme is the de-facto way of testing your React app. It’s pretty magical in that it renders your React components within Jest, allowing you to test your front end JSX code effectively without manually transpiling it. You render your components using one of three methods: shallow, mount, or render.

是测试您的React应用程序的实际方法。 这非常神奇,因为它在Jest中呈现了您的React组件,使您无需手动转译就可以有效地测试前端JSX代码。 您可以使用以下三种方法之一来渲染组件:浅,安装或渲染。

SuperTest allows you to make API calls without actually making the call, by intercepting it. API calls can be expensive and/or slow for unit tests, so you won’t want to make the call and wait for the response. Otherwise, it’ll slow down your tests and take forever to run.

SuperTest通过拦截来允许您进行API调用而无需实际进行调用。 API调用对于单元测试而言可能既昂贵又缓慢,因此您不希望进行调用并等待响应。 否则,它将减慢您的测试速度,并导致永远运行。

这是我学到的 (Here’s what I’ve learned)

测试可防止回归 (Testing prevents regression)

Adding new features frequently breaks existing code, and having tests can prevent this from happening. Testing helps ensure that your code works as you intend it to. As simple as it may sound, that makes a world of difference.

添加新功能经常会破坏现有代码,并且进行测试可以防止这种情况的发生。 测试有助于确保您的代码按预期工作。 听起来似乎很简单,但却与众不同。

It may seem silly to hear that not all programmers can articulate the code they write, but it’s actually pretty common. How many times have you been asked to explain something you wrote on the fly under a strict deadline and found yourself stuttering to answer? Writing tests forces you to think clearly about what exactly your function is taking in as an argument and returning as an output.

听到并非所有程序员都能清楚地表达他们编写的代码,这似乎很愚蠢,但这实际上很常见。 在要求您严格解释最后期限的情况下,有多少次您要解释自己写的东西,却发现自己口吃不住? 编写测试会迫使您仔细考虑您的函数究竟将什么作为参数并作为输出返回。

Even if you do understand the purpose of each line of code, as time goes on, you’ll inevitably start to forget. Tests provide an important complement to documentation that helps you move back and forth between code bases quickly. Taking the time to write good, efficient tests allows you to refactor your code much more easily and develop with confidence.

即使您确实了解每一行代码的目的,随着时间的流逝,您也不可避免地会忘记。 测试是对文档的重要补充,可帮助您快速在代码库之间来回移动。 花时间编写良好,高效的测试可以使您更轻松地重构代码并充满信心地进行开发。

使用模拟和存根进行单元测试。 (Unit test with mocks and stubs.)

In a unit test, you test a specific piece of code one at a time. In any application, your code probably will make calls to and depend on other classes or modules. As these relationships between classes increase in complexity, it’ll obfuscate the source of bugs.

在单元测试中,您一次测试一个特定的代码段。 在任何应用程序中,您的代码可能都会调用并依赖于其他类或模块。 随着类之间的这些关系增加复杂性,它将掩盖错误的来源。

In order to isolate and debug effectively, you can replace these dependencies with a mock or a stub to control the behavior or output you expect.

为了有效地隔离和调试,可以使用模拟或存根替换这些依赖关系,以控制所需的行为或输出。

For example, let’s say you want to test the following method:

例如,假设您要测试以下方法:

import database from 'Database';import cache from 'Cache';
const getData = (request) => { if (cache.check(request.id)) { // check if data exists in cache  return cache.get(request.id); // get from cache } return database.get(request.id); // get from database};

Stub:

存根:

test('should get from cache on cache miss', (done) => { const request = { id: 10 }; cache.check = jest.fn(() => false);
getData(request); expect(database.get).toHaveBeenCalledWith(request.id); done();});

Mock:

嘲笑:

test('should check cache and return database data if cache data is not there', (done) => { let request = { id: 10 }; let dummyData = { id: 10, name: 'Foo' }  let cache = jest.mock('Cache'); let database = jest.mock('Database'); cache.check = jest.fn(() => false); database.get = jest.fn(() => dummyData);
expect(getData(request)).toBe(dummyData); expect(cache.check).toHaveBeenCalledWith(request.id); expect(database.get).toHaveBeenCalledWith(request.id); done();});

The main difference between the two lies in state vs behavioral manipulation.

两者之间的主要区别在于状态与行为操纵。

When using mocks, you replace the entire module with a mock object. A stub is a forced output of a function no matter the given input. Mocks are used to test if a function is being called with the right arguments, and stubs are used to test how a function operates on a given response. Stubs are used to validate the state of a method, whereas mocks are used to evaluate the behavior.

使用模拟时,可以用模拟对象替换整个模块。 无论给定输入如何,桩都是函数的强制输出。 模拟用于测试是否使用正确的参数调用了函数,而存根用于测试函数如何在给定的响应下运行。 存根用于验证方法的状态,而模拟用于评估行为。

Jest provides jest.fn, which has both basic mocking and stubbing functionality. A Jest mock can also stub method outputs, and in this case be both a mock and a stub.

Jest提供了jest.fn ,它具有基本的jest.fn和存根功能。 Jest模拟还可以对方法输出进行存根处理,在这种情况下,它既可以是模拟也可以是存根。

The concept of mocks in testing and how they differ from stubs can get pretty complex, so for a deeper dive, check out the links at the end!

测试中的模拟概念以及它们与存根的区别会变得非常复杂,因此,如果要进行更深入的研究,请查看最后的链接!

知道您不需要测试的内容。 (Know what you don’t need to test.)

You’ll want to test every method you write. But keep in mind that depending on your code base, 100% test coverage is unlikely and most times not even necessary.

您将要测试您编写的每种方法。 但是请记住,根据您的代码库,不可能100%覆盖测试,大多数情况下甚至没有必要。

With Jest, you can easily track your test coverage by adding a--coverage tag to your test script on your CLI. While this is a useful measure, take this with a grain of salt — the way Jest measures test coverage is through tracing the call stack, so a higher test coverage doesn’t necessarily mean your tests are effective.

使用Jest,您可以在CLI的测试脚本中添加--coverage标记,从而轻松跟踪测试范围。 尽管这是一个有用的措施,但要花一点点时间-Jest衡量测试覆盖率的方法是通过跟踪调用堆栈,因此更高的测试覆盖率并不一定意味着您的测试有效。

For example, in a previous project, I used a library to implement a carousel component. Within the component was a function to render a list based on an array. To increase test coverage, I wrote a test to count and compare the number of rendered items to the array. The carousel component modified the number of items being rendered on the DOM to be more than a 1:1 output, even though the implementation visually displayed the correct number of elements in the browser. I chose to forego the test coverage because it was essentially testing the carousel library instead of my code.

例如,在上一个项目中,我使用一个库来实现轮播组件。 组件内有一个基于数组呈现列表的函数。 为了增加测试覆盖率,我编写了一个测试以计算并比较渲染项目到数组的数量。 轮播组件将DOM上呈现的项目数修改为大于1:1的输出,即使该实现在浏览器中直观地显示了正确数量的元素。 我选择放弃测试范围,因为它实际上是在测试轮播库而不是我的代码。

Let’s assume a Listings component with a method renderCarousel that renders a carousel from an external library:

让我们假设一个Listings组件带有一个renderCarousel方法,该方法从外部库中呈现一个轮播:

Ineffective test:

测试无效:

test('should return the same number of elements as the array', (done) => {    // Full DOM render    let mountWrapper = mount(<Listings />);
// State change to trigger re-render    mountWrapper.instance().setState({ listings: [listing, listing, listing] });
// Updates the wrapper based on new state    mountWrapper.update();
expect(mountWrapper.find('li').length).toBe(3);    done();  })

Effective test:

有效测试:

test('should call renderCarousel method when state is updated', (done) => {    // Mock function inside component to track calls    wrapper.instance().renderCarousel = jest.fn();
// State change to trigger re-render    wrapper.instance().setState({ listings: [listing, listing, listing] });
expect(wrapper.instance().renderCarousel).toHaveBeenCalled();    done();  });

The difference between the two lies in what the tests are actually testing.

两者之间的区别在于测试实际测试的内容。

The first example evaluates the renderCarousel function, which calls the external library. The second test evaluates whether the renderCarousel is simply being called. Since the external libraries are somewhat akin to a black box of magic and are being tested by their own developers, it’s not necessary to write a test that makes sure it’s working correctly.

第一个示例评估renderCarousel函数,该函数调用外部库。 第二个测试评估是否只是简单地调用renderCarousel。 由于外部库有点类似于魔术的黑盒子,并且正在由其自己的开发人员进行测试,因此无需编写确保其正常工作的测试。

In this scenario, we only need to test that the library is being called and have faith that the library’s developers are handling the testing.

在这种情况下,我们只需要测试正在调用该库,并确信该库的开发人员正在处理测试。

Understanding what you do and don’t need to test lets you maximize your time to remove redundancies.

了解您要做的事情和不需要进行的测试,可以使您最大限度地利用时间来消除冗余。

精心设计的测试会导致精心设计的代码。 (Well-designed tests lead to well-designed code.)

Designing your code knowing you’ll have to write tests for it improves your code. This is known as test-driven development, which is supported by a wide margin of the coding community.

在设计代码时就知道您必须为此编写测试,从而可以改善代码。 这就是所谓的测试驱动开发,它得到了编码社区的广泛支持。

In order to appropriately unit test functions, you need to strip away logic and test one method at a time. This structure forces you to write modular code and abstract logic away from your components.

为了适当地对测试功能进行单元化,您需要剥离逻辑并一次测试一种方法。 这种结构迫使您编写远离组件的模块化代码和抽象逻辑。

As you think about your code in terms of writing tests, you’ll start to develop the habit of decoupling your code. I’ve discovered that writing your code this way seems to produce a story-like structure that’s both easier to write and easier to follow.

在考虑编写测试代码时,您将开始养成将代码分离的习惯。 我发现以这种方式编写代码似乎产生了一个类似故事的结构,既易于编写,又易于遵循。

Let’s consider a scenario where we’re calling an endpoint to fetch data from a database and formatting that data before we return it.

让我们考虑一个场景,在该场景中,我们调用端点从数据库中获取数据并在返回数据之前对其进行格式化。

Too much logic:

逻辑太多:

// Define endpointapp.get('/project', (request, response) => {  let { id } = request.params;  let query = `SELECT * FROM database WHERE id = ${id}`;    database.query(query)    .then((result) => {      const results = [];      for (let index = 0; index < data.length; index++) {        let result = {};        result.newKey = data[index].oldKey;        results.push(result);      }      response.send(results);    })    .catch((error) => {      response.send(error);    })  })

Easier to test:

更容易测试:

// Make call to database for dataconst getData = (request) => {  return new Promise((resolve, reject) => {    let { id } = request.params;    let query = `SELECT * FROM database WHERE id = ${id}`;    database.query(query)      .then(results => resolve(results))      .catch(error => reject(error));    };}
// Format data to send backconst formatData = (data) => {  const results = [];  for (let index = 0; index < data.length; index++) {    let result = {};    result.newKey = data[index].oldKey;    results.push(result);  }  return results;}
// Send back dataconst handleRequest = (request, response) => {  getData(request)  .then((result) => {    let formattedResults = formatData(result)    response.send(formattedResults);  .catch((error) => {    response.send(error);}
// Define endpointapp.get('/project', handleRequest);

While the second example is longer, it’s much easier to follow along. The logic is clearly abstracted and isolated, making it much easier to test.

尽管第二个示例更长,但更容易理解。 逻辑被清楚地抽象和隔离,使其更容易测试。

If you’re just starting out with testing/coding, it can be hard to discern what makes a well-designed test. You can’t write effective tests if your code isn’t designed well, but you can’t figure out what makes code suitable for the tests you can’t write! Fortunately, this leads to my last tip…

如果您只是从测试/编码开始,那么很难分辨出什么是设计良好的测试。 如果您的代码设计不当,您将无法编写有效的测试,但是您无法弄清楚是什么使代码适合您无法编写的测试! 幸运的是,这引出了我的最后一条提示……

在编写代码时编写测试 (Write tests as you code)

The best way to incorporate testing is to write it alongside your code. Otherwise, it’ll feel overwhelming when you write them all at once and have to go back and forth between all your test and method files.

合并测试的最佳方法是将其与代码一起编写。 否则,当您一次全部编写它们并且不得不在所有测试文件和方法文件之间来回切换时,会感到不知所措。

Many beginners make the mistake of treating tests as something you do after all your code is written. If you treat it as a task you do alongside your code, it not only improves your code but also makes writing them more achievable.

在编写所有代码之后,许多初学者会犯错误,将测试视为您要做的事情。 如果您将其视为与代码一起执行的任务,那么它不仅可以改善代码,还可以更轻松地编写代码。

In a system with cleanly abstracted APIs, you can test each class before moving on so you know which part of the logic is broken. For instance, my ‘get’ endpoint calls getData to interact with the database. I would write tests for getData first and make sure those are green. That way, I know that if any of my controller tests fail, it probably has to do with the way I’m calling getData.

在具有干净抽象的API的系统中,您可以在继续进行之前测试每个类,以便知道逻辑的哪一部分坏了。 例如,我的“ get”端点调用getData与数据库进行交互。 我会先为getData编写测试,并确保它们是绿色的。 这样,我知道如果我的任何控制器测试失败,则可能与我调用getData的方式有关。

Hopefully this write-up has helped you understand why testing is so useful and has equipped you with some tips on how to get started. This only hits the tip of the iceberg with testing, though! Here are some resources if you want to learn more:

希望这篇文章可以帮助您了解测试为什么如此有用,并为您提供了一些入门的技巧。 但是,这只是通过测试击中了冰山一角! 如果您想了解更多,这里有一些资源:

https://martinfowler.com/articles/mocksArentStubs.html

https://martinfowler.com/articles/mocksArentStubs.html

https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c

https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c

If you enjoyed this article, please click on the ?? and share to help others find it. Thanks for reading!

如果您喜欢这篇文章,请单击??。 并分享以帮助他人找到它。 谢谢阅读!

翻译自: https://www.freecodecamp.org/news/why-i-now-appreciate-testing-and-why-you-should-too-74d48c67ab72/

为什么测试喜欢ie

为什么测试喜欢ie_为什么我现在喜欢测试,以及为什么您也应该如此。相关推荐

  1. 测试对方喜不喜欢你软件,对方是否喜欢你测试题

    测试对方是否喜欢自己的心理测试题,就要题目和答案 你想知道他是真心待你吗,只要你伸出右手让对方握住五根手指的一根,就知道了 A 大拇指 B食指 C中指 D无名指 E小指 A 他几乎是对你死心塌地的哟! ...

  2. 高级人力资源管理最喜欢的工具;笔迹分析测试的六大好处

    高级人力资源管理最喜欢的工具:笔迹分析测试的六大好处 目前汉字笔迹学正在发展初期,需要更多人才来参与.北京笔迹分析认证培训网笔迹读心网(www.du-xin.com)侯彤妹近些年在不断地在市场和社会生 ...

  3. 对不起,我现在喜欢划船了,不喜欢爬山了

    我记得王石过去特别喜欢爬山,因而带动得整个中国企业家界兴起了爬山热. 现在王石不喜欢爬山了,而是喜欢划赛艇了. 做企业也是如此,时代在变化,客户口味也在变化,不是你不好了,而是我腻了. 有的企业就如爬 ...

  4. 小明特别喜欢打扑克牌,除了喜欢斗地主和德州扑克之外,还喜欢一种叫桥牌的游戏,桥牌的具体规则相当复杂,有叫牌、打牌和计分三个阶段,还有不断变化的局况,局况可能影响叫牌打牌策略。但是小明暂时不关心这一些,

    题目描述: 小明特别喜欢打扑克牌,除了喜欢斗地主和德州扑克之外,还喜欢一种叫桥牌的游戏,桥牌的具体规则相当复杂,有叫牌.打牌和计分三个阶段,还有不断变化的局况,局况可能影响叫牌打牌策略.但是小明暂时不 ...

  5. 学计算机的男生喜欢什么样的女生,男生喜欢女生的九种表现 男生对女生说的甜蜜情话...

    1.你那些恶作剧我是故意中招的,因为想看见你的笑颜. 2.推我一把叫我加油的,抱着我让我"不用硬撑也可以"的都是你. 3.跟着我,不喜欢吗?如果不喜欢那我就跟着你走. 4.如果你在 ...

  6. 喜欢你的人和你喜欢的人 前面 后面

    喜欢你的人和你喜欢的人 时至如今,经历的喜欢自己的人和自己喜欢的人. 也终于明白些微道理: 大部分被喜欢的人是在喜欢它的人的前面, 喜欢一个人可能很大一部分就是因为它在你前面时间比较长, 对它关注比较 ...

  7. 面向对象:如果你刚好喜欢我,而我又喜欢你,那我们就在一起吧。猿来就是你

    各位男生如果看到合适的女生,但自己 "下不了手",请可劲地介绍给你还单着的亲朋好友 ^_^  小帖士 1)男生和女生都可以报名参加面向对象,加入方式详见公号底部菜单  " ...

  8. 世间最没有道理的是喜欢?也对,喜欢这种东西讲道理做什么 (小康小白)

    我是小康小白,一个平平无奇的Java小白.热爱有趣的文字,生活和远方. 个人博客:https://blog.csdn.net/weixin_45791445 有问题欢迎QQ联系:1059320343 ...

  9. 你喜欢的只是那个不喜欢你的她

    你喜欢的只是那个不喜欢你的她 转自http://www.douban.com/note/265049076/ (一) 我和一位要好的哥们儿喝了很多酒,那会儿午夜十二点. 他跟我说大一的时候很喜欢一位姑 ...

最新文章

  1. 如果有电脑——计算机达人成长之路(36)
  2. SpringBoot配置属性之NOSQL
  3. 学习OpenCV——粒子滤波(网上两篇文章总结)
  4. git同一项目使用多个远程仓库
  5. java搜索文件夹中文件是否存在_java中判断文件文件夹是否存在的方法(附代码)...
  6. XDP/eBPF — 架构设计
  7. ASP程序实现网页伪静态页源代码
  8. Codeforces Global Round 10
  9. Network Emulation(网格模拟)
  10. 草稿 DataGridView 控件 1129
  11. linux下配置Java和Go环境
  12. linux7空闲内存,centos7 内存占用率高处理问题
  13. [运维笔记] PowerShell (模块).模块清单
  14. 《扩展 jQuery》——2.3 总结
  15. 阶段1 语言基础+高级_1-3-Java语言高级_05-异常与多线程_第3节 线程同步机制_2_线程安全问题的代码实现...
  16. BP神经网络代码实现
  17. HaaS EDU场景式应用整体介绍
  18. 计算机基础到底是哪些基础?为什么很重要!
  19. 微信小程序: 赞赏码的长按识别
  20. 破解Windows7开机密码

热门文章

  1. HTML如何添加锚点,我先收藏为敬
  2. 我的MarkDown入门
  3. 如何写一个vue指令directive
  4. C/C++查找一定范围内的素数(筛法)
  5. UVA 662 Fast Food
  6. 个人材料(上报公司)
  7. 软件公司管理基本原则
  8. 长春南关区净月大街附近都有哪些课后班?
  9. 文字创作类App分享-简书
  10. 币氪共识指数排行榜0910