在 chai 测试框架中使用 chai-things 插件

阅读时长 5 min read

介绍

chai-things 是一个用于扩展 chai.js 断言库的插件,它允许我们查询集合中是否包含目标元素、是否存在特定属性等等。这个插件在处理包含数组和对象的集合时非常方便。

安装

在使用 chai-things 插件前,需要先安装 Chai 断言库。

然后安装 chai-things 插件:

使用

在测试文件中引入 Chai 断言库和 chai-things 插件:

include.something

include.something 用于判断一个集合中是否包含目标元素。

include.all.members

include.all.members 用于判断一个集合中是否包含所有指定元素。

contain.a.thing.with.property

contain.a.thing.with.property 用于判断一个集合中是否存在元素,该元素拥有指定的属性。

注意事项

  • 当使用 includecontain 时,集合中的元素顺序不影响测试结果。

  • 当使用 include.something 进行测试,如果集合中存在多个目标元素,则仅仅会测试到第一个目标元素。

  • 当使用 contain.a.thing.with.property 进行测试,如果集合中存在多个拥有指定属性的元素,则仅仅会测试到第一个元素。

示例代码

假设我们有一个名为 getUsers 的方法,用于获取用户列表:

我们可以使用 chai-things 插件测试该方法的返回值:

-- -------------------- ---- -------
-------------------- -- -- -
  ---------- ------ -- ----- ---- -------- --------- ---- -------- ---------- ---- ------ ------- -- -- -
    ----- ----- - -----------
    
    --------------------------------
    ---------------------------------------------------------------- -------
  ---

  ---------- ------ -- ----- ---- -------- --- ------- ------- --------- -- -- -
    ----- --------- - ------- --------
    ----- ----- - -----------
    
    --------------------------------
    ------------------------------------------------
  ---

  ---------- ------ -- ----- ---- -------- - ----- ---- -------- ---------- ---- ------ ------ --- -------- ----- ---- ------ ---- -- -- -
    ----- ----- - -----------
    
    --------------------------------
    ---------------------------------------------------------- --------------------------- ----
  ---
---

运行测试:

-- -------------------- ---- -------
- ----- -------


  --------
    - ------ ------ -- ----- ---- -------- --------- ---- -------- ---------- ---- ------ -----
    - ------ ------ -- ----- ---- -------- --- ------- ------- -------
    - ------ ------ -- ----- ---- -------- - ----- ---- -------- ---------- ---- ------ ------ --- -------- ----- ---- ------ --


  - ------- ------

总结

chai-things 插件为 chai.js 断言库提供了方便的集合测试方法。我们可以使用 include.somethinginclude.all.memberscontain.a.thing.with.property 等方法进行测试,实现方便高效的集合测试。在使用过程中需要注意注意事项,避免出现误判的情况。

Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/64703a78968c7c53b0e5bd1b

Feed
back