Mocha是否支持多个在创建独立http服务器之前使用的钩子?

时间:2018-08-13 02:30:36

标签: mocha

这是我的项目结构:

src/
 - demo-1/
   - server.ts
   - server.spec.ts
 - demo-2/
   - server.ts
   - server.spec.ts

每个server.spec.ts都具有以下设置:

import { start } from './server';

let server: http.Server; 
before('start server', (done: Done) => {
  server = start(done);
});

after('stop server', (done: Done) => {
  server.close(done);
});

describe('test suites', () => {
  //...
})

这是我的package.json scripts

"scripts": {
    "test": "NODE_ENV=test mocha --timeout=3000 --require=ts-node/register ./src/**/*.spec.ts"
  },

我运行npm test时出现错误:

 1) "before all" hook: start server:
     Uncaught Error: listen EADDRINUSE :::4000
      at Object._errnoException (util.js:1022:11)
      at _exceptionWithHostPort (util.js:1044:20)
      at Server.setupListenHandle [as _listen2] (net.js:1351:14)
      at listenInCluster (net.js:1392:12)
      at Server.listen (net.js:1476:7)
      at Function.listen (node_modules/express/lib/application.js:618:24)
      at Object.start (src/constructor-types/server.ts:33:14)
      at Context.before (src/constructor-types/server.spec.ts:12:12)
      at Server.app.listen (src/aliases/server.ts:42:7)
      at emitListeningNT (net.js:1378:10)
      at _combinedTickCallback (internal/process/next_tick.js:135:11)
      at process._tickCallback (internal/process/next_tick.js:180:9)

  2) "after all" hook: stop server:
     Error: Not running
      at Server.close (net.js:1604:12)
      at emitCloseNT (net.js:1655:8)
      at _combinedTickCallback (internal/process/next_tick.js:135:11)
      at Immediate._tickCallback (internal/process/next_tick.js:180:9)

我希望每个server.spec.ts独立工作,这意味着启动服务器并逐个运行其测试套件,以避免HTTP端口冲突。因为这些服务器具有相同的http端口。

1 个答案:

答案 0 :(得分:0)

Mocha并行运行测试文件。服务器将同时创建到一个端口中。 解决方法是为每个文件分配随机端口(更改start函数以添加动态端口参数)

import { start } from './server';

const PORT = Math.floor((Math.random() * 100000) + 1);

let server: http.Server; 

before('start server', (done: Done) => {
  // change start function accept port param
  server = start(PORT, done);
});

after('stop server', (done: Done) => {
  server.close(done);
});

另一种解决方案是serial-mocha,它支持运行测试同步。但是这个包是旧的,我不知道它是否仍然可以使用