MongoMemoryServer;未处理的错误

时间:2019-04-28 12:10:32

标签: typescript express testing jestjs

我正在用jest,supertest和mongo-memory-server测试Typescript express-mongoose应用程序。所有测试都通过了,但是在使用mongo-memory-server的每个测试中都出现此错误。 我发现mongoose.disconnect导致了它,但我仍然无法修复它

import { MongoMemoryServer } from 'mongodb-memory-server';
let mongoServer: any;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 600000;
describe('createUser', (): void => {
  let mongoServer: any;
  const opts = {}; 
  beforeAll(async () => {
    mongoServer = new MongoMemoryServer();
    const mongoUri = await mongoServer.getConnectionString();
    await mongoose.connect(mongoUri, opts, err => {});
  });

  afterAll(async () => {
    mongoose.disconnect();
    await mongoServer.stop();
  });

  it('creating user', async (): Promise<void> => {
    const email = 'test@mail.com';
    const username = 'testUser';
    const password = 'testPassword';
    const { userId } = await createUser(email, username, password);
    expect(userId).toBeTruthy();
    expect(typeof userId).toMatch('string');
  });
});
console.error node_modules/jest-jasmine2/build/jasmine/Env.js:289
   Unhandled error
    console.error node_modules/jest-jasmine2/build/jasmine/Env.js:290
      Error [ERR_UNHANDLED_ERROR]: Unhandled error. (MongoNetworkError: read ECONNRESET)
          at Connection.emit (events.js:178:17)
          at Socket.<anonymous> (C:\Users\PC\Desktop\typescript-mern-budget-app\server\node_modules\mongodb-core\lib\connection\connection.js:321:10)
          at Object.onceWrapper (events.js:277:13)
          at Socket.emit (events.js:189:13)
          at emitErrorNT (internal/streams/destroy.js:82:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
          at process._tickCallback (internal/process/next_tick.js:63:19)

1 个答案:

答案 0 :(得分:0)

afterAll(async () => {
  await mongo.stop();
  await mongoose.connection.close();
});

问题是您没有等待这两个功能。