Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
How to mock MongoDB client event listeners?

I am confused when trying to mock event listeners using jest. Any suggestions are welcome.

MongoDB Node.js Driver version 4.1.2

index.js

const { MongoClient } = require('mongodb');
const service = {
  name: 'mongo',
  created() {
    this.client = new MongoClient('mongodb://localhost:27017');
  },
  async started() {
    this.client = await this.client.connect();
    this.client.on('error', () => console.error('MongoDB error'));
    this.client.on('close', () => console.log('MongoDB closed'));
  },
};

module.exports = service;

index.spec.ts

This test I try to raise error event after the service broker is started and write specified error message to console.

test('should write error to console', async () => {
  const broker = new ServiceBroker({ logger: false });
  broker.loadService(`${process.cwd()}/index.js`);
  const services = broker.services.filter(
    (service) => service.fullName === 'mongo'
  );
    
  const connectSpy = jest.spyOn(services[0].client, 'connect');
  connectSpy.mockResolvedValue({
    db: jest.fn().mockReturnValue({
          collection: jest.fn(),
    }),
    on: jest.fn(),
  });

  await broker.start();
  expect(connectSpy).toHaveBeenCalled();

  /**
   * TODO: simulate mongo client error event
   *
   * emit mongo client error
   * then assert expect(clientSpy.on).toHaveBeenCalled()
   * or expect(someObj).toBe('MongoDB error')
   */
}

Live Demo

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!