单个Jest集成测试有效,但多个测试失败

时间:2020-01-19 11:38:37

标签: javascript express mongoose jestjs

我的Jest集成测试有一个奇怪的问题。如果我一个接一个地运行测试,它们将顺利通过。如果我一次性运行多个测试,它们将失败,并报告“随机”问题。随机的,因为失败的测试次数随每次运行而变化。因此,如果我多次运行同一组测试,它可能一次报告31个失败的测试,而下一次报告17个失败的测试。

鉴于所报告的行为,我怀疑存在一些时间安排或缓存问题。因为在下一次运行时前一个测试似乎还没有完全完成,因此会引起问题。我认为我已经构建了我的测试来防止这种情况的发生,但是显然不是这种情况...

我用来启动测试的Jest调用看起来像这样:jest --verbose --detectOpenHandles --testRegex '/test/integration/sc.*\\.test\\.js' (我也尝试在其中添加--runInBand,但是对于出现的问题并没有影响)

我的Jest集成测试都具有相同的结构。我将向您展示其中两个的开始:

const request = require('supertest');
const {Score } = require('../../models/score');

describe('/api/scores', () => {
  let server; 

  beforeEach(async () => { 
    delete require.cache[require.resolve('../../index')];    
    server = await require('../../index'); 
  });

  afterEach(async () => { 
    await Score.deleteMany({}).exec();
    await server.close(); 
  });  

  afterAll(async () => { 
    delete require.cache[require.resolve('../../index')];    
    server = await require('../../index'); 
    Score.collection.drop();
    await server.close();
  });

  describe('GET /', () => {
     ...

const request = require('supertest');
const { Sessie } = require('../../models/sessie');
const { Check } = require('../../models/check');
const { Opdracht } = require('../../models/opdracht');
const { Score } = require('../../models/score');
const { Speler } = require('../../models/speler');

describe('/api/sessies', () => {
  let server; 

  beforeEach(async () => { 
    delete require.cache[require.resolve('../../index')];    
    server = await require('../../index'); 
  });

  afterEach(async () => { 
    await Sessie.deleteMany({}).exec();
    await Check.deleteMany({}).exec();
    await Opdracht.deleteMany({}).exec();
    await Score.deleteMany({}).exec();
    await Speler.deleteMany({}).exec();
    await server.close(); 
  });  

  afterAll(async () => { 
    delete require.cache[require.resolve('../../index')];    
    server = await require('../../index'); 
    Sessie.collection.drop();
    Check.collection.drop();
    Opdracht.collection.drop();
    Score.collection.drop();
    Speler.collection.drop();
    await server.close();
  });

  describe('GET /', () => {
     ...

也许我会为所有的deleteMany和collection删除而烦恼,但我只是想真正确保不同的测试不会污染彼此的结果。

哦,“ ../../ index”的要求用于启动快递服务器:

const express = require('express');
const cors = require('cors')
const app = express();
app.use(cors());

[...]

const port = process.env.PORT || 3000;
const server = app.listen(port, () => logger.info(`Listening on host [...] and port ${port}...`));

module.exports = server;

(我运行Express 4.17,Mongoose 5.6.8和Jest 24.9)

为什么我的测试会连续失败,但是当我分别运行它们时却不会失败?

0 个答案:

没有答案