1. const assert = require('assert').strict;
    2. /*
    3. # 生命周期执行测试
    4. 测试before执行时机1
    5. 测试beforeEach执行时机2
    6. ✓ 1 加 1 应该等于 2
    7. 测试afterEach执行时机3
    8. # indexo f测试
    9. # indexOf测试测试before执行时机1
    10. 测试beforeEach执行时机2
    11. # indexOf测试测试beforeEach执行时机2
    12. ✓ indexOf测试
    13. # indexOf测试测试afterEach执行时机3
    14. 测试afterEach执行时机3
    15. # indexOf测试测试after执行时机4
    16. 测试after执行时机4
    17. */
    18. describe('# 生命周期执行测试', function () {
    19. before('before', function () { // 运行测试之前执行
    20. console.log('测试before执行时机1');
    21. });
    22. beforeEach('beforeEach', function () { // 在每个测试用例之前执行。
    23. console.log('测试beforeEach执行时机2');
    24. });
    25. after('after', function () { // 运行测试之后执行
    26. console.log('测试after执行时机4');
    27. });
    28. afterEach('afterEach', function () { // 在每个测试用例之后执行。
    29. console.log('测试afterEach执行时机3');
    30. });
    31. it('1 加 1 应该等于 2', function () {
    32. assert(1 + 1 === 2);
    33. });
    34. const publishApiName = '# index测试';
    35. describe(publishApiName, function () {
    36. before('before', function () {
    37. console.log(`${publishApiName}测试before执行时机1`);
    38. });
    39. beforeEach('beforeEach', function () {
    40. console.log(`${publishApiName}测试beforeEach执行时机2`);
    41. });
    42. after('after', function () {
    43. console.log(`${publishApiName}测试after执行时机4`);
    44. });
    45. afterEach('afterEach', function () {
    46. console.log(`${publishApiName}测试afterEach执行时机3`);
    47. });
    48. it('indexOf测试', function () {
    49. assert.strictEqual([1, 2, 3].indexOf(4), -1);
    50. });
    51. });
    52. });
    53. /**
    54. * 异步的测试
    55. */
    56. describe('#异步的测试', function () {
    57. this.timeout(6000); // 可以通过此方法设置超时时间
    58. // this.timeout(0); // 禁用超时
    59. before('before', function (done) { // 异步的生命周期,这里可以放connect数据库
    60. setTimeout(function () {
    61. done();
    62. // 超过2秒 就会抛出 Error: Timeout of 2000ms exceeded.
    63. // For async tests and hooks, ensure "done()" is called;
    64. // if returning a Promise, ensure it resolves.
    65. }, 1500);
    66. });
    67. beforeEach('before', function (done) { // 异步的生命周期,这里可以放connect数据库
    68. // this.timeout(2000); // 挂钩级超时也可能适用
    69. setTimeout(function () {
    70. done();
    71. }, 1500); // 超过2秒抛出异常
    72. });
    73. it('promise异步测试', function (done) { // done可以传入两个参数,第一个参数如果不是null或undefined,表示测试用例执行失败,第二个参数是回调函数
    74. new Promise(function (res, reject) {
    75. try {
    76. // assert(1 === 2);
    77. res();
    78. } catch (err) {
    79. reject(new Error(err));
    80. }
    81. }).then(function () {
    82. done();
    83. }).catch(function (err) {
    84. done(err);
    85. });
    86. }).timeout(6000); // 可以指定单个it的超时时间
    87. });
    88. // 可以异步执行用例
    89. // $ mocha --delay xxx.js
    90. setTimeout(function () {
    91. if (run) {
    92. run();
    93. }
    94. }, 5000);