node.js - 运行具有相同上下文的多个 mocha 文件和套件
问题描述
我正在尝试使用一些共享上下文运行几个集成测试。共享的上下文是一个单一的快速应用程序,我试图在套件/文件之间共享它,因为它需要几秒钟才能启动。
我通过实例化一个“运行器”mocha 测试套件来使其工作,该套件将具有测试功能,可以require
根据需要仅对每个测试文件进行测试,并且效果很好(副作用是需要子测试文件的测试将完成为在文件中的任何测试实际运行之前“成功”,但这是一个小问题)
// test-runner.js:
describe('Integration tests', function () {
let app
let log
this.timeout(300000) // 5 mins
before(function (done) {
app = require('../app')
app.initialize()
.then(() => {
done()
})
.catch(err => {
log.error(err)
done(err)
})
})
it('Running api tests...', (done) => {
require('./integration/api.test')(app)
done()
})
// ./integration/api.test.js:
module.exports = (app) => {
let api = supertest.agent(app)
.set('Content-Type', 'application/json')
describe('Authorization', () => {
describe('Trying to access authorization sections', () => {
it('should be denied for /home', async () => {
await api.get(`${baseUrl}/home`)
.expect(STATUS_CODE.UNAUTHORIZED)
})
...
问题:
我想通知测试运行程序导入套件中的所有测试都已完成,因此我可以在测试运行程序中调用关闭逻辑并干净地结束测试。在标准测试函数中,您可以传递一个done
函数来表示测试中的代码已完成,因此我将每个子测试包装在一个描述块中,以使用after
钩子来表示整个测试模块已完成:
// test-runner.js:
describe('Integration tests', function () {
let app
let log
this.timeout(300000) // 5 mins
before(function (done) {
app = require('../app')
app.initialize()
.then(() => {
done()
})
.catch(err => {
log.error(err)
done(err)
})
})
it('Running api tests...', (done) => {
require('./integration/api.test')(app, done)
})
// ./integration/api.test.js:
module.exports = (app, done) => {
let api = supertest.agent(app)
.set('Content-Type', 'application/json')
describe('All api tests', () => {
let api
before(() => {
api = supertest.agent(app)
.set('Content-Type', 'application/json')
})
after(() => {
done() // should be calling the done function passed in by test runner
})
describe('Authorization', () => {
describe('Trying to access authorization sections', () => {
it('should be denied for /home', async () => {
await api.get(`${baseUrl}/home`)
.expect(STATUS_CODE.UNAUTHORIZED)
})
...
但是当我这样做时,测试套件就不会运行。默认超时将过期,如果我设置了更高的超时,它只是坐在那里(等待更长的超时)。如果我挂钩到调试会话,那么测试会立即退出,并且后挂钩(和之前!)永远不会被调用。
我也对如何做到这一点持开放态度,但我还没有找到任何好的解决方案,可以在测试之间共享一些上下文,同时将它们分成不同的文件。
解决方案
推荐阅读
- c# - 如何使用事件处理程序将数据从一个表单传输到另一个表单
- java - 连接到 MSSQL 消耗太多内存
- angular - 编译角度测试时如何排除文件
- c# - 安装程序后如何获取资源的文件(-path)
- jquery - 将动态 lat/lng 转换为 Open Layer 脚本
- hadoop-yarn - 纱线 - yarn.scheduler.capacity.root.queue-name.maximum-capacity 是如何工作的?
- python - 按过滤器删除无但不删除 0
- sql-server - SMO - 如何以动态 SQL 样式编写对象脚本?(如果不存在)
- kubernetes - 为多个命名空间创建 serviceaccount
- angular - 用户输入时如何获取选项值