测试用例编写

大家好,我是万维读客的讲师曹欢欢。本节主要学会如何编写简单的测试用例,能把整个项目环境跑通,保证我们的测试用例可以正常执行。

增加指令

package.json里面增加test指令,用于我们启动测试用例执行。

{
  "name": "treact",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "test": "vitest",
    "preview": "vite preview"
  },
  "devDependencies": {
    "happy-dom": "^12.10.3",
    "vite": "^5.0.8",
    "vitest": "^1.1.0"
  }
}

然后开启测试用例执行:

npm run test

编写用例

新建treact01文件夹,新建tdd.test.js文件,内容如下:

import {describe, it, expect} from 'vitest';

describe('Tdd Test',()=>{
    it('works', ()=>{
        const a = 'hello world';
        expect('hello world').toBe(a);
        expect('hello world').equals(a);
    })
})

查看测试用例输出,输出结果如下:

(base) ➜  treact npm run test

> treact@0.0.0 test
> vitest


 DEV  v1.1.0 /Users/w3cdoc/work/treact

 ✓ treact01/tdd.test.js (1)
   ✓ Tdd Test (1)
     ✓ works

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  16:03:52
   Duration  629ms (transform 29ms, setup 0ms, collect 15ms, tests 5ms, environment 201ms, prepare 140ms)


 PASS  Waiting for file changes...
       press h to show help, press q to quit

异步函数测试用例

因为后面fiber需要用到异步处理,这里我们测试下异步的测试用例,增加测试用例如下:

function wait(item){
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            resolve(1);
        }, 500);
    });
}
describe('Tdd Test',()=>{
    it('sync works', ()=>{
        const a = 'hello world';
        expect('hello world').toBe(a);
        expect('hello world').equals(a);
    });
    it('async works', async()=>{
        const a = await wait();
        expect(a).toBe(1);
    })
})

查看控制台输出:

 RERUN  treact01/tdd.test.js x3

 ✓ treact01/tdd.test.js (2) 505ms
   ✓ Tdd Test (2) 504ms
     ✓ sync works
     ✓ async works 501ms

 Test Files  1 passed (1)
      Tests  2 passed (2)
   Start at  19:47:54
   Duration  516ms


 PASS  Waiting for file changes...
       press h to show help, press q to quit

参考学习

  1. TDD: https://juejin.cn/post/6844903780970921991
  2. vitest: https://vitest.dev/guide/why.html
  3. vite: https://vitejs.dev/guide/why.html


请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部