如何首先将 mocha 设置为 运行 单元测试,然后启动服务器和 运行 集成测试

How to setup mocha to run unit tests first and then start a server and run integration tests

我有单元测试和集成测试需要 运行 使用一个 'npm run mocha' 命令。我的集成测试之前的套件已设置并与 mocha.opts 一起正常工作,包括像这样的前一步:

test/beforeTests.js (sets up some important variables)
test/*.x.js (bulk of the tests, all the files ending in .x.js are run)

当包括我的集成测试时,单元测试失败,因为 运行ning 服务器与一些存根函数冲突。因此我想先 运行 单元测试,然后启动服务器,运行 集成测试并关闭服务器。我尝试将 mocha.opts 更改为:

test/beforeTests.js (sets up some important variables)
test/*.x.js (bulk of the tests, all the files ending in .x.js are run)
test/startServer.js (start the server)
test/integration/*.x.js (run integration tests)
test/afterTests.js (close the server)

beforeTests.js:

before(function(done) { 
 // do something 
});

startServer.js:

before(function() {
 return runServer()
});

beforeTests 和 startServer 都可以工作,但是它们都在测试开始时执行,而不是

beforeTest > do unit tests > start server > do integration tests > stop server

我无法将集成测试合并到一个文件中,或者单元测试太多了。有没有办法设置 mocha.opts 来做我想做的事。我环顾四周,没有真正适合我想做的事情。

我之前为此使用的技术之一是有两个 npm 命令用于单元测试和集成测试,然后如果我想 运行 它们在单次执行中将它们组合在一个 npm 命令中。

"test": "npm run test:unit && npm run test:integration"
"test:unit": "mocha test/unit",
"test:integration": "mocha test/integration"

您可以启动服务器作为 integration 测试的一部分。

我建议对 npm test 使用 test 而不是对 npm run mocha 使用 mocha 因为它是节点项目中更标准的测试命令名称。

希望对您有所帮助