发布于 2026-01-06 0 阅读
0

在下一个库的开发中使用 API 优先和 TDD。TDD 可能不是合适的起点,API 优先可以解决这个问题。下一步:覆盖率和变异测试。总结

在你的下一个库中使用 API 优先和 TDD 模式

TDD可能不是最合适的入门工具

API 先来救援

下一阶段:覆盖率和突变测试

综上所述

我运用这种技巧来帮助我创建更相关的单元测试,我想和大家分享一下。

如果您对TDD不太熟悉,请查看这篇简明扼要的文章:

TDD可能不是最合适的入门工具

假设我们正在构建一个 Node 模块,用于检查某个日期是否在两个日期之间。我们称它为is-date-between……

我们现在就来编写单元测试。

...

听起来很复杂,不是吗?

API 先来救援

我们换个角度来看:请给我举个使用这个库的例子。

const isDateBetween = require('is-date-between');

const dateToCheck = new Date('2018-12-26');
const pastDate = new Date('2017-01-01');
const futureDate = new Date('2019-01-01');

console.log(isDateBetween(dateToCheck, pastDate, futureDate)); // true
Enter fullscreen mode Exit fullscreen mode

由此我们可以推断出我们想要避免的不同问题:

  • 过去和未来的日期不应该被调换。
  • 所有参数都应该是日期对象
  • 检查应全面彻底。

其转录形式为:

const chai = require('chai');
const expect = chai.expect;
const isDateBetween = require('is-date-between');

describe('isDateBetween', function() {
  it('should throw an exception if the past & future dates are reverted', function() {
    expect(function() {
      const dateToCheck = new Date('2018-12-26');
      const pastDate = new Date('2017-01-01');
      const futureDate = new Date('2019-01-01');

      isDateBetween(dateToCheck, futureDate, pastDate);
    }).to.throw('dates are reverted');
  });

  it('should throw an exception if the date to check is not a date object');
  it('should throw an exception if the past date is not a date object');
  it('should throw an exception if the future date is not a date object');
  it('should return true if the date to check is between');
  it('should return false if the date to check is not between');

  describe('inclusive dates', function() {
    it('should return true if the date to check is equal to the past date');
    it('should return true if the date to check is equal to the future date');
  });
});
Enter fullscreen mode Exit fullscreen mode

看,你做到了!

下一阶段:覆盖率和突变测试

测试依赖于人。而人天生不完美,我们会遗忘,会犯错,也会做不相关或重复的工作……

有些工具可以帮助你限制这种情况,直到埃隆·马斯克把我们变成半机械人为止。

代码覆盖率可以让你检查代码中哪些部分尚未经过测试。这有助于你覆盖尽可能多的用例。我喜欢nyc,因为它与mocha兼容性很好

变异测试是一个强大的工具,可以用来检查你是否测试了代码中正确的部分。它会稍微修改你的源文件,并检查是否有测试失败:如果没有,说明你可能忽略了一些测试,而这些测试本应允许变异通过。这对于帮助我们提高单元测试的质量非常有帮助。我很喜欢Stryker 。

综上所述

2019 年的测试不应该令人畏惧,而应该触手可及。我认为我们往往把事情想得比实际情况复杂得多。我希望 API 优先的理念能够激发你开始使用测试的兴趣(如果你以前从未接触过测试的话)。

测试需要花费更多时间,但当你需要扩展功能和修复漏洞时,这些时间就物有所值了。实际上,它还能让你对产品的后续版本更有信心,因为你可以依靠测试来构建坚实的基础。

如果你曾经想过

最好不要改动这部分代码,它太复杂了,如果添加任何东西都可能导致出错。

或许现在是时候考虑单元测试了 ;)

文章来源:https://dev.to/anwar_nairi/using-api-first-and-tdd-for-your-next-library-49c2