jest

配置

目标:可以使用npm run test和vscodeJest Runner插件。 Jest RunnerJest要好,尤其是你在写测试用例的时候,试试就知道了。

  1. 基本配置
    初始化配置文件输入jest --init
    jest 三种配置模式:js / ts / package.json 的 jest 字段。建议使用 ts,因为有类型提示的支持

  2. Jest Runner配置
    首先设置:
    image.png

    testing library

    https://juejin.cn/post/6907052045262389255
    测试框架实际上有很多,且非唯一解。

    testing library 意图让你通过用户使用 app 的方式去做测试。react testing library 也一样,只提供 dom 的操作。 但是它们忘了一个问题:开发者也是用户的一种。 所以要对 react 组件做测试,很大程度上还需要 enzyme 的配合。

查询

可以使用Testing Playground浏览器插件帮助写查询。

查询策略

testing library 对于查询分为以下基本六种

  1. 单一元素

getBy...:找到一个元素并返回。找不到或多于一个都会报错。
queryBy...: 找到一个元素并返回。找不到返回null,多于一个会报错。
findBy...: 返回promise,1000ms 内持续查找,找到一个元素并返回。找不到或多于一个都会拒绝。

  1. 多元素

getAllBy...: 返回查询到的元素数组。找不到会报错
queryAllBy...: 返回查询到的元素数组。找不到返回空数组。
findAllBy...: 返回promise,1000ms 内持续查找,返回查询到的元素数组。找不到会拒绝。

Type of Query 0 Matches 1 Match >1 Matches Retry (Async/Await)
Single Element
getBy… Throw error Return element Throw error No
queryBy… Return null Return element Throw error No
findBy… Throw error Return element Throw error Yes
Multiple Elements
getAllBy… Throw error Return array Return array No
queryAllBy… Return [] Return array Return array No
findAllBy… Throw error Return array Return array Yes

查询内容

[ByDisplayValue](https://testing-library.com/docs/queries/bydisplayvalue)
可以查input``textarea``select的值
[ByAlt](https://testing-library.com/docs/queries/byalttext)``[ByTitle](https://testing-library.com/docs/queries/bytitle)

快照测试

这里使用了@testing-library/react作为react测试库(和jest官网文档中的不一样)

  1. afterEach(cleanup)
  2. test("itemSnapshot", () => {
  3. const { asFragment } = render(<Editor data={Items} schema={$Items} />)
  4. expect(asFragment()).toMatchSnapshot()
  5. })

enzyme

安装

安装enzyme和adapter,以及在setup配置adapter

自动化测试的一些问题

代码重构之后:
有时候不知道是你测试文件写错了还是代码写错了
有时候你的测试文件都有漏洞,只能过之前的测试,重构之后,即使没在数据结构上加新特性且兼容之前功能,新代码也过不了。
尤其是你测试时生成的用户等数据结构,都偷懒不完善,后面功能完善了,看这些数据结构的时候,测试代码就错了