yaofly2012 / note

Personal blog
https://github.com/yaofly2012/note/issues
44 stars 5 forks source link

JS-单元测试(Unit Test) #137

Open yaofly2012 opened 4 years ago

yaofly2012 commented 4 years ago

JS单元测试(Unit Test, UT)

一、理论(TDD,BDD)

  1. TDD(Test-driven Development)
  2. BDD(Behavior-driven Development)

前端单元测验 TDD Vs BDD

二、JS测试框架Jest/Mocha/Ava的简单比较

三、如何写UT?

  1. 分析代码,画出各个逻辑分支
yaofly2012 commented 4 years ago

Jest学习

路线:

  1. 基础
    • 基本概念
    • 基本用法
  2. 异步代码测试
  3. Mock
  4. 其他项目整合
  5. API

一、基本概念

1.1 test suite 测试套件

  1. 一个test文件就是一个test suite
  2. test suite可以视为一个无形的Root Describe

查找test suite

  1. 没有test suite时执行jest会提示:

    testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 0 matches
    testPathIgnorePatterns: \\node_modules\\ - 3 matches
    testRegex:  - 0 matches
    • jest会根据文件名字自动查找当前目录下所有test suites;
    • 会忽略node_modules目录。
  2. 默认的匹配规则:[ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]

    • __tests__目录下的.js, .jsx, .ts, .tsx文件;
    • 带有test或则spec后端的.js, .jsx, .ts, .tsx文件。

1.2 describe

  1. describe可以对测试用例(test)进行分组,也定义了hooks作用域。
  2. describe可以嵌套,即describe里除了可以包含tests, hooks之外还可以包含子describe

1.3 Hooks & 作用域

  1. 每个describe或者test的执行前后都有Hook函数,通过Hook函数可以执行一些公共逻辑,比如:初始化,资源释放等。
    • beforeAll, beforeEach
    • afterAll, afterEach

这里的AllEach指的是test

  1. Hooks是声明在Describe里的(Test suite视为Root Describe),Hooks的作用域就是其Describe块。

1.4 test, it

  1. testit用来声明具体的测试用例。
  2. What is the difference between 'it' and 'test' in jest?
    • 两者在功能上是等价的:it只是test的别名;
    • it's about readability not about functionality

区别在于表达的方式:

// test if xxxx
describe('yourModule', () => {
  test('if it does this thing', () => {});
  test('if it does the other thing', () => {});
});

// it should xxxx
describe('yourModule', () => {
  it('should do this thing', () => {});
  it('should do the other thing', () => {});
});

1.3 Matchers:匹配器

  1. 诊断真实值
  2. 一个test里可以有多个匹配器,只有当所有匹配器通过才算是test通过;
  3. Jest只支持BDD写法expect