《Node.js 单元测试(Mocha / Jest)》

《Node.js 单元测试(Mocha / Jest)》

1. describe/it 用法:只运行部分用例

只运行指定的测试套件

describe('Array', function() { describe.only('#indexOf()', function() { // 只有这个 suite 会被执行 }); });

只运行某个测试用例

describe('Array', function() { describe('#indexOf()', function() { it.only('should return -1 unless present', function() { // 只有这条用例会被执行 }); it('should return the index when present', function() { // 被跳过 }); }); });

2. console.log 调试

可以直接调用 console.log() 输出调试信息,但必须在末尾加上分号,否则可能报找不到该函数:

console.log('hello');

3. before/after 钩子

Mocha 提供 before()、after()、beforeEach()、afterEach(),用于在测试前后准备/清理:

describe('hooks', function() { before(function() { // runs before all tests in this block }); after(function() { // runs after all tests in this block }); beforeEach(function() { // runs before each test in this block }); afterEach(function() { // runs after each test in this block }); // test cases });

执行顺序:before() → beforeEach() → 用例 → afterEach() → after()。

参考:https://mochajs.org/#hooks

4. 字符串包含子串断言(chai)

expect('foobar').to.include('foo');

参考:https://www.chaijs.com/api/bdd/

5. 文档

  • jest:https://jestjs.io/docs/en/cli
  • mocha:https://mochajs.org/
阅读 — · 全站 —
🎸 我的歌单 0 首