在测试列表操作之外使用断言库

Using assertion library outside of testing for list manipulations

本文关键字:断言 测试 列表 操作      更新时间:2023-09-26

在我目前的项目中,我在前端做了很多列表操作,我意识到使用chai或其他断言库可以节省我很多时间,并使代码相当可读。

虽然Chaijs很酷,但它的api并不完全是功能和curry友好的。我的问题是:

在测试环境之外寻找用于数组操作/过滤的断言库实际上是一个好主意吗?还是我在吸可卡因?

如果有的话,有没有人在图书馆有成功的故事?

我想做的一些简单的例子:

const people = [
  {name: "David Smith", age: 25, livedIn: ["London", "Paris"]},
  {name: "John Smith", age: 30, livedIn: ["New York"]},
  {name: "John Gates", age 25, livedIn: ["London", "New York"]}
]

目前我们使用的是普通闭包,当检查足够容易时,一切都很好,很闪亮:

people
  // Let's find 25 year olds
  .filter((person) => person.age === 25);
  // And see who is among them john
  .filter((person) => person.name.indexOf("John") === 0);

现在一切都很简单,但是接下来我们需要开始测试深层属性:person.names.firstName,或person.cities[<index>].postCode,这就是断言库在纸上做得很好,chai或jasmine有方法来做这件事,来自chaaijs文档的例子:

expect(tea).to.have.property('flavors').with.length(3);

例如,使用断言库,我可以找到住在伦敦的人:

people
  .filter((person) => {
    return expect(person.livedIn).to.includes("London");
  });

或者not lived in London:

people
  .filter((person) => {
    return expect(person.livedIn).not.to.includes("London");
  });

当然还有范围:

expect({price: 50}).to.be.within(40, 60);

现在,虽然chaijs和jasmine在功能上都是我需要的,但它们的API不起作用,我希望API接近Ramda或可组合函数,首先是规则,最后是迭代。类似以下语句:

people
   .filter(within('age', 20, 40)) // Filter age property, to be 20 < age < 40
   .filter(contains('livedIn', 'London', 'Boston')) // Further filter people, by place they lived in.

当然我不想要也不需要那个API。它可以有任何不同,只要我能处理它

出于这个目的,我绝对不会在您的活动代码中包含断言库。像Lodash这样的库有一些有用的函数可以使用:

people
   .filter(p => _.inRange(p.age, 20, 40))
   .filter(p => _.intersection(['London', 'Boston'], p.livedIn).length > 0)

这可能不是您想要的语法。然而,函数式编程的好处是,编写一些自己的函数来生成您正在寻找的过滤器是非常容易的。

filters = {
    within: (property, low, high) => {
        return (obj) => {
            return obj[property] >= low && obj[property] <= high;
        };
    },
    ...
};
people
   .filter(filters.within('age', 20, 40)) // Filter age property, to be 20 < age < 40