尝试使用 jest 模拟事件侦听器时,我感到很困惑。欢迎任何建议。
MongoDB Node.js 驱动程序版本 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;
索引.spec.ts
此测试我尝试在服务代理启动后引发错误事件并将指定的错误消息写入控制台。
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')
*/
}