英文:
Testing EventEmitter event handlers
问题
Here's the translated code portion you requested:
我想测试事件处理(测试连接建立后是否已订阅):
```javascript
import * as mqtt from 'mqtt';
export function testEmitter() {
console.info(`连接到MQTT服务器 ${process.env.MQTT_URL} ...`);
const client = mqtt.connect(process.env.MQTT_URL, {
username: process.env.MQTT_USER,
password: process.env.MQTT_PASS,
clientId: process.env.MQTT_CLIENT ?? 'checkmk_zigbee2mqtt',
});
client.on('connect', () => {
console.info(`订阅MQTT主题 ...`);
client.subscribe(`${process.env.SOME_TOPIC}/#`, { rh: 1, qos: 0 }, () => {});
});
}
我的jest代码如下:
export class MqttClientMock extends events.EventEmitter {
subscribe = jest.fn((topic: string, opts: any, callback: ClientSubscribeCallback) => {
callback(undefined, []);
});
publish = jest.fn();
unsubscribe = jest.fn();
}
describe('emitterTests', () => {
const mqtt = require('mqtt');
let client: MqttClientMock;
beforeEach(() => {
client = new MqttClientMock();
mqtt.connect = jest.fn();
})
it('应在连接建立后订阅', (done) => {
testEmitter();
expect(mqtt.connect).toBeCalled();
client.emit('connect', new Error('你做错了'));
expect(client.subscribe).toBeCalled();
done();
})
});
我无法在我所做的任何尝试中创建有效的测试。
上述实现会给出错误消息:TypeError: Cannot read properties of undefined (reading 'on')
其他尝试(例如将testEmitter异步化)告诉我,日志记录'订阅MQTT主题 ...'是在终止后完成的。
我该如何编写一个有效的测试来验证连接后的处理?
请注意,上述代码仅为您提供了翻译后的部分,不包括回答您要翻译的问题。如果您需要进一步的解释或帮助,可以随时提出。
<details>
<summary>英文:</summary>
I want to test handing of an event (test if I have subscribed after a connection has been established):
import * as mqtt from 'mqtt';
export function testEmitter() {
console.info(Connecting to MQTT Server ${process.env.MQTT_URL} ...
);
const client = mqtt.connect(process.env.MQTT_URL, {
username: process.env.MQTT_USER,
password: process.env.MQTT_PASS,
clientId: process.env.MQTT_CLIENT ?? 'checkmk_zigbee2mqtt',
});
client.on('connect', () => {
console.info(`Subscribing to MQTT topic ...`);
client.subscribe(`${process.env.SOME_TOPIC}/#`, { rh: 1, qos: 0 }, () => {});
};
My jest code looks like:
export class MqttClientMock extends events.EventEmitter {
subscribe = jest.fn((topic: string, opts: any, callback: ClientSubscribeCallback) => {
callback(undefined, []);
});
publish = jest.fn();
unsubscribe = jest.fn();
}
describe('emitterTests', () => {
const mqtt = require('mqtt');
let client: MqttClientMock;
beforeEach(() => {
client = new MqttClientMock();
mqtt.connect = jest.fn();
})
it('should subscribe after the connection is established', (done) => {
testEmitter();
expect(mqtt.connect).toBeCalled();
client.emit('connect', new Error('you did wrong'));
expect(client.subscribe).toBeCalled();
done();
})
});
I am not able to create a valid test on any attempt that I made.
Above implementation gives error message: `TypeError: Cannot read properties of undefined (reading 'on')`
Some other attempts (i.e. making testEmitter async) tell me that logging 'Subscribing to MQTT topic ...' is done after termination
How can I write a good test that validates the handling after a connect?
</details>
# 答案1
**得分**: 0
你应该在 `beforeEach` 中模拟 `mqtt.connect` 后,将 `client` 设置为 `mqtt.connect` 的返回值吗?
<details>
<summary>英文:</summary>
Shouldn't you set `client` as the return value for `mqtt.connect` after mocking it in `beforeEach`?
beforeEach(() => {
client = new MqttClientMock();
mqtt.connect = jest.fn();
mqtt.connect.mockReturnValue(client)
})
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论